Python token的获取和再次登录验证

from flask import Flask, jsonify, g
from flask_script import Manager
from flask_httpauth import HTTPBasicAuth
from flask_restful import Api,Resource
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

auth = HTTPBasicAuth()
#认证的回调函数
@auth.verify_password
def verify_password(username_or_token,password):
    if username_or_token == "wangbo" and password == "123456":
        g.username = username_or_token
        print(username_or_token)
        return True
    #再次尝试token
    s = Serializer(app.config["SECRET_KEY"])
    try:
        print("88888")
        print(username_or_token.encode("utf8"))
        data = s.loads(username_or_token.encode("utf8"))
        g.username = data["username"]

        return True
    except:
        print("789")
        return False
#认证失败的时候可以定制
@auth.error_handler
def unauthorized():
    return jsonify({"error":"Unauthorized"})

api = Api()
app = Flask(__name__)
manager = Manager(app)
app.config["SECRET_KEY"] = "123456"
#2.创建资源
class UserAPI(Resource):
    def get(self, uid):
        return {"user":"获取单个"}
    def put(self, uid):
        return {"user":"修改"}
    def delete(self, uid):
        return {"user":"删除"}
class UserList(Resource):
    decorators = [auth.login_required]
    def get(self):
        return {"user":"获取所有"}
#单个添加post请求添加认证
    #@auth.login_required

    def post(self):
        return {"user":"post请求"}
#3.添加资源管理器
api.add_resource(UserAPI, "/user//")
api.add_resource(UserList, "/user/")
api.init_app(app)
#获取token
@app.route("/get_token/")
@auth.login_required
def get_token():
    s = Serializer(app.config["SECRET_KEY"], expires_in=3600)
    #print(s)
    token = s.dumps({"username":g.username})
    #print(token)
    return jsonify({"token":token.decode("utf8"),"expires":3600})

if __name__ == '__main__':
    manager.run()

你可能感兴趣的:(Python,token)