【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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM