码迷,mamicode.com
首页 > 其他好文 > 详细

flask-restful

时间:2020-02-12 13:18:13      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:password   out   tor   类库   多个   except   返回   auth   serialize   

from flask import Flask,jsonify,g
#导入restful类库
from flask_restful import Api,Resource
from flask_httpauth import HTTPBasicAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer



app = Flask(__name__)



#创建认证对象
auth = HTTPBasicAuth()

#设置认证的回调函数,需要认证时自动回调,成功返回true,失败返回flase
@auth.verify_password
def verify_password(username_or_token,password):
    if username_or_token == bill and password == 123456:
        return True
    else:
        if check_token(username_or_token):
            return True
        return False

#认证的错误显示
@auth.error_handler
def unauthorized():
    return jsonify({error:认证失败}),403

#生成token
app.config[SECRET_KEY] = 123456
def generate_token(expires_in=3600):
    s = Serializer(app.config[SECRET_KEY],expires_in=expires_in)
    return s.dumps({username:jerry,password:123456})

#校验token
def check_token(token):
    s = Serializer(app.config[SECRET_KEY])
    try:
        data = s.loads(token)
    except:
        return False
    g.username = data.get(username)
    return True

#创建api对象
api = Api(app)


@app.route(/token)
@auth.login_required
def get_token():
    #return jsonify({‘token‘:generate_token()})
    return generate_token()

#创建资源,继承自Resource
class UserAPI(Resource):
    def get(self,id):
        return {User:GET}
    def put(self,id):
        return {User:PUT}
    def delete(self,id):
        return {User:DELETE}

class UserListAPI(Resource):
    #添加认证(资源保护),最简单的认证,传输的时候不够安全
    decorators = [auth.login_required]
    def get(self):
        #return {‘UserList‘:‘GET‘}
        return {User: g.username}
    def post(self):
        return {UserList:POST}


#添加资源
#参数:1、资源类名,2、路由地址,可以是多个路由,访问相同地址,3、端点
api.add_resource(UserAPI,/user/<int:id>,endpoint=user)
api.add_resource(UserListAPI,/user/,endpoint=users)




if __name__ == __main__:
    app.run(debug=True)

 

flask-restful

标签:password   out   tor   类库   多个   except   返回   auth   serialize   

原文地址:https://www.cnblogs.com/bill2014/p/12298413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!