首页 > 解决方案 > 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该类。

标签: pythonpython-3.xflask

解决方案


Flask 具有before_requestafter_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功能将其传递给流程中的其他路由。


推荐阅读