python – 密码保护Flask应用程序中的一个网页
发布时间:2020-12-20 12:08:02 所属栏目:Python 来源:网络整理
导读:我正在运行Flask Web应用程序并使用Apache基本身份验证(使用.htaccess和.htpasswd文件)来对其进行密码保护.我想密码保护应用程序中的一个网页.当我用密码保护网页的html文件时没有任何效果,网页仍然没有密码保护.这可能是因为我的 python文件是使用render_te
我正在运行Flask Web应用程序并使用Apache基本身份验证(使用.htaccess和.htpasswd文件)来对其进行密码保护.我想密码保护应用程序中的一个网页.当我用密码保护网页的html文件时没有任何效果,网页仍然没有密码保护.这可能是因为我的
python文件是使用render_template调用html文件的吗?我不知道如何解决这个问题.
解决方法
您需要限制对端点的访问.
This snippet应该让你开始走正确的道路.
from functools import wraps from flask import request,Response 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 有了这个,您可以使用@requires_auth修饰要限制的任何端点. @app.route('/secret-page') @requires_auth def secret_page(): return render_template('secret_page.html') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |