flask 實現 Authorization請求報頭認證

#!/usr/bin/env python
#! coding=utf-8
#! [email protected]
from functools import wraps
from flask import request, Response,Flask
app = Flask(__name__)

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == 'admin' and password == 'secret'

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route('/user')
@requires_auth    
def show_user_profile():
    return 'open page!!' 

if __name__=='__main__':
    app.run(host='0.0.0.0',port=6666,debug=True)

詳情請參照:http://flask.pocoo.org/snippets/8/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章