1. 程式人生 > >Flask-HTTP驗證方法

Flask-HTTP驗證方法

安裝和啟用

先通過pip來安裝擴充套件:Flask-HTTPAuth

 pip install Flask-HTTPAuth

建立物件,並設定自定義處理方法

根目錄下

app\token.py

from flask import jsonify, g,current_app
from flask_httpauth import HTTPBasicAuth,HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from app.db import Db
import hashlib

#認證賬戶名和密碼
auth = HTTPBasicAuth()

#認證token
token_auth = HTTPTokenAuth(scheme='Bearer')


@auth.verify_password
def verify_password(username, password):
    app=current_app._get_current_object()
    password = hashlib.new('md5',password.encode('utf8')).hexdigest()
    admin = Db.table('bn_admin_user').where({'username':username,'password':password}).find()
    if admin:
        g.username = username
        g.admin_id = admin['id']
        return True
    return False


@auth.error_handler
def unauthorized():
    return jsonify({'code':'403','msg': '賬戶名或者密碼錯誤'}), 403


@token_auth.verify_token
def verify_token(token):
    app = current_app._get_current_object()
    s = Serializer(app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
        g.username = data['username']
        g.admin_id = data['admin_id']
        return True
    except:
        return False


@token_auth.error_handler
def unauthorized():
    return jsonify({'code':'403','msg': 'token認證失敗'}), 403









在模型中使用藍圖設定路由並繫結驗證

from flask import g,jsonify
from flask import Blueprint
from app.token import token_auth
from app.auth import ver_auth
main = Blueprint('main',__name__)



#請求路由前處理繫結
@main.before_request
#驗證token裝飾器
@token_auth.login_required
#許可權驗證
@ver_auth




@main.route('/',methods=['GET','POST'])
def index():
    return  '首頁'


@main.route('/aa',methods=['GET','POST'])
def aa():
    return  '測試'