1

我正在用 Flask 构建一个基本应用程序:它有一个唯一的路由,只请求一个令牌身份验证,即如果标头中提供的令牌是正确的,那么请求就得到了满足。为此,我同时安装了FlaskFlask-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)初始化

4

1 回答 1

1
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

安全=安全(应用程序,用户数据存储)

于 2015-10-11T13:35:51.873 回答