zoukankan      html  css  js  c++  java
  • 【flask】RestFul的基本鉴权

    编写API的基本鉴权

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Author : shenqiang
    
    from flask import Flask,make_response,jsonify
    from flask_restful import  Resource,Api,reqparse
    from flask_httpauth import HTTPBasicAuth
    
    '''实例化Flask这个类'''
    app = Flask(__name__)
    '''调用flask Restful'''
    api = Api(app=app)
    '''调用鉴权'''
    auth = HTTPBasicAuth()
    '''解决jsonify中文显示乱码问题'''
    app.config['JSON_AS_ASCII']=False
    app.config['DEBUG']=True
    
    '''输入账号密码认证,否者报错提示请认证'''
    @auth.get_password
    def get_password(username):
        if username == 'shenqiang':
            return 'admin'
    
    @auth.error_handler
    def authorized():
        return make_response(jsonify({'msg':'你好,请认证'}),401)
    
    '''页面报错404的友好提示'''
    @app.errorhandler(404)
    def notFound(error):
        '''函数必须添加:error'''
        return make_response(jsonify({'error':'this page is not found'}),404)
    
    '''页面报错405的友好提示'''
    @app.errorhandler(405)
    def notFound(error):
        '''函数必须添加:error'''
        return make_response(jsonify({'error':'该请求方法错误'}),405)
    
    '''配置index路由器'''
    '''添加登录鉴权资源'''
    @app.route('/index')
    @auth.login_required
    def index():
        return jsonify({'status':0,'msg':'success','datas':{'userid':1003,'name':'shenqiang','age':'18'}})
    
    if __name__ == '__main__':
        app.run(debug=True)
  • 相关阅读:
    前进篇
    2014年12月14日记
    转载了两篇别人写的话语
    想好了,也决定了
    活着
    c#字典排序
    插值转向
    unity手游使用terrian注意事项
    委托delegate 泛型委托action<> 返回值泛型委托Func<> 匿名方法 lambda表达式 的理解
    推荐博客关于uniy
  • 原文地址:https://www.cnblogs.com/shen-qiang/p/12030396.html
Copyright © 2011-2022 走看看