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)