python - 使用烧瓶用户登录/身份验证保护页面
问题描述
我已经用烧瓶做了很多开发,但还没有深入研究使用用户身份验证来保护 Web 应用程序。为了这个例子,假设我有基本的设置
from flask import Flask
app = Flask(__name__)
# Can't be accessed if not logged in
@app.route('/secure')
def secure():
# pseudo code
if user != authenticated:
return redirect('login')
else:
return render_template('secure.html')
@app.route('/login')
def login():
return render_template('login.html')
# Called from the login page form
@app.route('/authenticate')
def authenticate():
# do some code to authenticate, pseudo
if username in DB and password == password-hash:
user = authenticated
return redirect('/')
if __name__ == '__main__':
app.run()
我能够使用 mongodb 并添加/删除/查询数据。我的问题是我不知道如何将两者联系在一起。用户创建一个帐户,将数据添加到数据库,用户登录,对数据库查询的输入,如果匹配,他们就可以访问该站点。
我遇到的问题是如何让我的 Flask 应用程序知道在用户提供正确的凭据以记住/知道他们是谁并允许他们访问受限页面之后。我想在他们注销之前如何跟踪身份验证状态。
注意:想知道 Flask 中最安全的多用户认证方法
解决方案
您需要一个处理 http 方法的 API。Flask-restful 和 Flask-httpauth 你可以编写如下代码:
@marshal_with(piece_fields)
@auth.login_required
def post(self):
args = self.reqparse.parse_args()
piece = models.Piece.create(**args)
return piece, 201,
{'Location': url_for('resources.pieces.Piece', id=Piece.id)}
@auth.login_required 是基本或令牌 http 身份验证(在名为 auth.py 的单独文件中定义),其中包含您的 http 方法。他们将要求使用用户名和密码或令牌发送 http 请求。希望这可以帮助!
推荐阅读
- python - Python计算递归调用的迭代次数
- swift - 打开子菜单时的 Swift UIMenu 视觉故障
- java - 如何根据日期和时间自动标记数组列表中的相关记录?
- sapui5 - SmartFilterBar 日期字段显示格式
- javascript - node.js 模块/需要索引 es5 支持我自己的复杂库
- flutter - 文本字段上的颤动光标位置
- haskell - 如何让 `elem` 在 1-50 而不是 1-9 的列表之间检查我的输入?它拒绝任何超过个位数的东西
- docker - Docker Redis 容器 - 命令选项
- javascript - 位置对象中的 react-router-dom slug 为空
- c++ - 尝试在 C++ 代码中运行 C++ 可执行文件会停止程序