我正在使用Flask构建一个基本应用程序:它有一个唯一的路由,只请求令牌身份验证,即如果标头中提供的令牌是正确的,则请求得到满足。为此,我安装了Flask
和Flask-Security
。这是我的应用的片段:
from flask import Flask
from flask.ext.security import auth_token_required
from flask.ext.security import Security
app = Flask(__name__)
app.config['SECURITY_TOKEN_AUTHENTICATION_KEY'] = 'mytoken'
security = Security(app)
@app.route('/myurl')
@auth_token_required
def myrequest():
return 'OK'
if __name__ == '__main__':
app.run(debug=True)
我通过运行来测试它:
$ curl -H 'Authorization: Token token="mytoken"' localhost:5000/myurl
甚至:
$ curl localhost:5000/myurl
但是,我收到以下错误:
Traceback (most recent call last):
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 113, in decorated
if _check_token():
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 50, in _check_token
header_key = _security.token_authentication_header
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 24, in <lambda>
_security = LocalProxy(lambda: current_app.extensions['security'])
KeyError: 'security'
你知道错误在哪里吗?它是在应用程序中还是在Flask库中的某些冲突中?
编辑:添加了Security(app)
初始化
答案 0 :(得分:1)
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security =安全(app,user_datastore)