我正在使用Flask,而我只是做了以下教程:https://www.youtube.com/watch?v=J5bIPtEbS0Q
这是代码:
from flask import Flask, jsonify, request, make_response
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisthesecretkey'
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.args.get('token')
if not token:
return jsonify({'message' : 'Token is missing!'}), 403
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
except:
return jsonify({'message' : 'Token is invalid'}), 403
return f(*args, **kwargs)
@app.route('/unprotected')
def unprotected():
return jsonify({'message' : 'Anyone can view this!'})
@app.route('/protected')
@token_required
def protected():
return jsonify({'message' : 'This is only available for people with valid tokens.'})
@app.route('/login')
def login():
auth = request.authorization
if auth and auth.password == 'asdf':
token = jwt.encode({'user' : auth.username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
return jsonify({'token' : token.decode('UTF-8')})
return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
if __name__ == '__main__':
app.run(debug=True)
我做了视频中的所有操作,但出现以下错误:
/home/one/systemx/test_api$ python flask_authentication.py
Traceback (most recent call last):
File "flask_authentication.py", line 31, in <module>
@token_required
File "/home/one/.local/lib/python2.7/site-packages/flask/app.py", line 1250, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/home/one/.local/lib/python2.7/site-packages/flask/app.py", line 66, in wrapper_func
return f(self, *args, **kwargs)
File "/home/one/.local/lib/python2.7/site-packages/flask/app.py", line 1180, in add_url_rule
endpoint = _endpoint_from_view_func(view_func)
File "/home/one/.local/lib/python2.7/site-packages/flask/helpers.py", line 90, in _endpoint_from_view_func
assert view_func is not None, 'expected view func if endpoint ' \
AssertionError: expected view func if endpoint is not provided.
有人知道问题出在哪里吗?
我发现错误出在第30行:
@token_required
当我添加它时。
但是我不知道为什么。