from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,get_jwt_identity
)
import datetime
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!
jwt = JWTManager(app)
# Using the expired_token_loader decorator, we will now call
# this function whenever an expired but otherwise valid access
# token attempts to access an endpoint
@jwt.expired_token_loader
def my_expired_token_callback(expired_token):
token_type = expired_token['type']
return jsonify({
'status': 401,
'sub_status': 42,
'msg': 'The {} token has expired'.format(token_type)
}), 401
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
if username != 'test' or password != 'test':
return jsonify({"msg": "Bad username or password"}), 401
ret = {'access_token': create_access_token(username)}
return jsonify(ret), 200
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return jsonify({'hello': 'world', 'nowTime': nowTime}), 200
@app.route('/create-dev-token', methods=['POST'])
@jwt_required
def create_dev_token():
username = get_jwt_identity()
expires = datetime.timedelta(minutes=1)
token = create_access_token(username, expires_delta=expires)
return jsonify({'token': token}), 201
if __name__ == '__main__':
app.run()
过期处理
Reads: 1200
Edit
Comments
Make a comment
www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。
本网站与其它任何公司及/或商标无任何形式关联或合作。