我們正在使用 Python Quart 開發 API。我們有多個路由設定和全域錯誤處理方法
@app.errorhandler(InternalServerError)
def handle_error(error):
<logging and return server error code>
我們需要一種通過向請求物件添加隨機散列來標記每個請求的方法。因此可以通過訪問請求物件在任何地方訪問它。例如,錯誤處理程式應該能夠訪問每個請求標記的隨機散列。
使用 Quart API 框架實作這一目標的最簡潔方法是什么。我們希望在沒有任何意外副作用的情況下實作這一目標。
uj5u.com熱心網友回復:
這里有一個完整的基于對Request物件進行子類化的解決方案,根據內部Quart注釋是首選方法。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390004.html
