我正在开发一个带有蓝图的Flask
0.12应用,我正在尝试使用Flask-JWT
(0.3.2)进行身份验证。
我可以看到Flask-JWT的所有教程都没有使用蓝图。
每个示例中通常都有一段代码,它们执行以下操作:
app = Flask(__name__)
jwt = JWT(app, authenticate, identity)
在蓝图烧瓶应用程序中,结构倾向于更像这样:
__初始化__吡啶:
from swarm.controllers.main import main
from swarm.controllers.grid import grid
from swarm.controllers.address import address
def create_app(object_name):
app = Flask(__name__)
...
app.register_blueprint(main)
app.register_blueprint(grid)
app.register_blueprint(address)
控制器/ main.py:
main = Blueprint('main', __name__)
控制器/ grid.py:
grid = Blueprint('grid', __name__)
控制器/ address.py:
address = Blueprint('address', __name__)
我如何引用Flask-JWT
并在控制器中使用其装饰器?
通过展示如何将JWT装饰器添加到烧瓶源代码o blueprintexample中的Michał Karzyński's REST API demo等标准示例,可能更容易回答这个问题。
答案 0 :(得分:4)
我已经构建了一个允许使用Flask-JWT
装饰器的简单示例。
文件结构:
server
├── app
| ├── admin # blueprint
| | ├── __init__.py
| | ├── views.py
| ├── __init__.py
├── config.py
└── run.py
首先,创建一个名为admin
的蓝图并导入其视图
# file: server/app/admin/init.py
from flask import Blueprint
admin = Blueprint('admin', __name__)
from . import views
admin
蓝图有一个视图。在这里,我们导入admin
蓝图和一些flask_jwt
内容,以便我们可以正确访问他们的装饰器:
from flask_jwt import jwt_required, current_identity
from . import admin
# file: server/app/admin/views.py
@admin.route('/protected')
@jwt_required()
def protected():
return '%s' % current_identity
现在创建烧瓶应用,创建JWT
实例,并将admin
蓝图注册到烧瓶应用程序:
# file: server/app/__init__.py
from flask import Flask
from flask_jwt import JWT
from werkzeug.security import safe_str_cmp
from .admin import admin
# skipping over jwt authenticate() and identity() creation
# https://pythonhosted.org/Flask-JWT/
# ...
app = Flask(__name__)
app.config.from_object('config')
jwt = JWT(app, authenticate, identity)
app.register_blueprint(admin, url_prefix='/admin')
最后,设置脚本管理器:
from flask_script import Manager, Server
from server.app import app
manager = Manager(app)
# Turn on debugger by default and reloader
manager.add_command("runserver", Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 5000)
)
if __name__ == "__main__":
manager.run()
现在,如果我们转到我们的/ admin / protected url,我们会看到JWT启动并运行:
{
"description": "Request does not contain an access token",
"error": "Authorization Required",
"status_code": 401
}
我希望这有帮助!