python - Flask API - 验证哈希请求
问题描述
在我的烧瓶 API 应用程序中,我想验证客户端发送的哈希。如果客户端发送了不正确的哈希,我想立即返回一条错误消息。哈希是由客户端和我的应用程序共享的预定义计算生成的。
在下面的示例中,它在Controller
返回结果的类中实例化new_configuration
。
以干净、优雅和集中的方式验证哈希(考虑到我有多个这样的方法)的最佳方法是什么,而不为每个方法使用 if 语句?
@app.route('/newRegistration', methods=['POST'])
def new_registration():
controller = Controller()
return jsonify(controller.new_configuration(request.json))
注意:我所有的路由方法都调用Controller
该类。
解决方案
Flask 具有before_request
,after_request
以及更多可以帮助您管理它的功能。
使用示例:
# routes that won't be hash validated
PUBLIC_ROUTES = ["/favicon.ico", "/"]
@app.before_request
def validate_hash():
# avoid validating on public routes
for route in PUBLIC_ROUTES:
if route == request.path:
return
hash = g.params.get("hash", None)
# validate hash exists in request
if not hash:
raise BadRequestError("Missing hash")
if hash != DEFAULT_HASH:
raise UnauthorizedError("Hash is invalid")
在PUBLIC_ROUTES
对方法中未声明的烧瓶路由的每个请求将被执行之前,并将尝试验证在请求中收到的哈希参数
关于您的笔记,您可以添加另一个before_request
初始化控制器并使用flask.g
功能将其传递给流程中的其他路由。
推荐阅读
- c# - 如何使用 c# 使用 HttpWebResponse 制作 api
- lisp - Lisp,计算混合表达式
- flutter - Flutter中WIFI可用时缓存和刷新API调用数据的最佳方法?
- mysql - 选择除子查询中指定的行之外的所有行
- c - 从 C 中的 Cygwin 路径中退出
- database - 计算 B+ 树内存使用量(最小值、最大值)
- javascript - 打字稿命名空间参考不起作用
- scala - 如何在 apache zeppelin 0.8.2 上使用带有 Scala 2.12 的 spark 将 spark 3.x 提交给 yarn?
- java - 为什么在尝试清除 Canvas 时出现错误(Nullpointerexception)?
- vue-component - 在单独的 Vue 组件中单击按钮加载另一个 Vue 组件