Combining Flask Blueprints with Flask-JWT
I've built a simple example that enables use of Flask-JWT
decorators.
The file structure:
server├── app| ├── admin # blueprint| | ├── __init__.py| | ├── views.py| ├── __init__.py├── config.py└── run.py
First, create a blueprint called admin
and import its views
# file: server/app/admin/init.pyfrom flask import Blueprintadmin = Blueprint('admin', __name__)from . import views
The admin
blueprint has one view. Here, we import the admin
blueprint and some flask_jwt
stuff so we can properly access their decorators:
from flask_jwt import jwt_required, current_identityfrom . import admin# file: server/app/admin/views.py@admin.route('/protected')@jwt_required()def protected(): return '%s' % current_identity
Now create the flask app, create the JWT
instance, and register the admin
blueprint to the flask application:
# file: server/app/__init__.pyfrom flask import Flaskfrom flask_jwt import JWTfrom werkzeug.security import safe_str_cmpfrom .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')
And finally, set up your script manager:
from flask_script import Manager, Serverfrom server.app import appmanager = Manager(app)# Turn on debugger by default and reloadermanager.add_command("runserver", Server( use_debugger = True, use_reloader = True, host = '0.0.0.0', port = 5000))if __name__ == "__main__": manager.run()
Now, if we go to our /admin/protected url, we will see that JWT is up and running:
{ "description": "Request does not contain an access token", "error": "Authorization Required", "status_code": 401}
I hope this helps!