【问题标题】:Add data to request in the route handler using Python Quart使用 Python Quart 在路由处理程序中向请求添加数据
【发布时间】:2022-01-22 19:21:12
【问题描述】:

我们正在使用 Python Quart 开发 API。 我们有多个路由设置和全局错误处理方法

@app.errorhandler(InternalServerError)
def handle_error(error):
    <logging and return server error code>

我们需要一种通过向请求对象添加随机散列来标记每个请求的方法。因此可以通过点击请求对象在任何地方访问它。例如,错误处理程序应该能够访问标记为每个请求的随机哈希。

使用 Quart API 框架实现这一目标的最简洁方法是什么。我们希望在没有任何意外副作用的情况下实现这一目标。

【问题讨论】:

    标签: python python-3.x api rest quart


    【解决方案1】:

    这里有一个基于Request对象子类化的完整解决方案,根据内部Quart cmets是首选方法。

    https://pgjones.gitlab.io/quart/reference/source/quart.html https://github.com/pgjones/quart/blob/main/src/quart/wrappers/request.py

    在此实现中,“correlation_id”需要从 request.args 中获取或动态生成,并且应附加到请求上下文中,以便在代码或错误处理等请求中普遍使用。

    (注意:“ABC”导入避免了一些 Python 抽象类的问题,并且不必重新实现抽象方法。)

    QuartUtilities.py:

    from abc import ABC
    from typing import cast
    from uuid import uuid4
    
    # Subclass of Request so we can add our own custom properties to the request context
    class CorrelatedRequest(Request, ABC):
        correlation_id: str = ""
    
    
    def correlate_requests(app: Quart):
        app.request_class = CorrelatedRequest
    
        @app.before_request
        def ensure_correlation_id_present():
            correlated_request = cast(CorrelatedRequest, request)
            if correlated_request.correlation_id != "":
                return
    
            if 'correlation_id' in request.args:
                correlated_request.correlation_id = request.args["correlation_id"]
            else:
                correlated_request.correlation_id = uuid4()
    
    
    def get_request_correlation_id() -> str:
        return cast(CorrelatedRequest, request).correlation_id
    
    

    QuartPI.py:

    
    from quart import Quart
    from werkzeug.exceptions import InternalServerError
    from QuartUtilities import correlate_requests
    
    app = Quart(__name__)
    correlate_requests(app)
    
    @app.errorhandler(InternalServerError)
    def handle_error(error):
        correlation_id = get_or_create_correlation_id()
    
    

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      相关资源
      最近更新 更多