pipinstallflask-httpauth基于简单密码的认证fromflask_httpauthimportHTTPBasicAuthauth=HTTPBasicAuth()@auth.verify_passworddefverify_password(username,password):user=User.query.filter_by(username=username).first()ifnotuserornotuser.verify_password(password):returnFalseg.user=userreturnTrue通过实现verify_password回调函数去验证用户名和密码,验证通过返回True,否则返回False。然后Flask-HTTPAuth再调用这个回调函数,这样就可以轻松自定义验证方法。如果用户名与密码验证通过,user对像会被存储到Flask的g对像中。(注:对象g存储在应用上下文中而不再是请求上下文中,这意味着即使在应用上下文中它也是可访问的而不是只能在请求上下文中。)方便其它函数使用。@app.route('/api/resource')@auth.login_requireddefget_resource():returnjsonify({'data':'Hello,%s!'%g.user.username})让我们使用已经注册的用户来请求看看:$curl-uok:python-i-XGEThttp://127.0.0.1:5000/api/resourceHTTP/1.0200OKContent-Type:application/jsonContent-Length:30Server:Werkzeug/0.9.4Python/2.7.3Date:Thu,28Nov201320:02:25GMT{"data":"Hello,ok!"}如果登录错误,会返回以下内容:$curl-umiguel:ruby-i-XGEThttp://127.0.0.1:5000/api/resourceHTTP/1.0401UNAUTHORIZEDContent-Type:text/html;charset=utf-8Content-Length:19WWW-Authenticate:Basicrealm="AuthenticationRequired"Server:Werkzeug/0.9.4Python/2.7.3Date:Thu,28Nov201320:03:18GMTUnauthorizedAccess