我正在学习FastAPI,遇到了一个被卡住的场景。我想实现一个逻辑,其中每个 API 端点都有其 API Credits (int),我将在 HTTP 中间件中使用它从用户的余额中扣除积分。我进行了很多搜索,但一直无法得到任何解决方案。谁能帮助我实现这一目标?我提供伪代码来解释我想要实现的目标。
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
# here I want to read API credits for request
print(request.api_credit)
response = await call_next(request)
return response
@app.post("/myendpoint1")
async def myendpoint1():
# define api credit for this endpoint
api_credit = 2
return {"message": "myendpoint"}
@app.post("/myendpoint2")
async def myendpoint2():
# define api credit for this endpoint
api_credit = 5
return {"message": "myendpoint2"}
request.state
存储任意状态并在中间件和API端点之间传输数据。请参阅这些答案以了解更多详细信息。
因此,你可以有这样的东西:
from fastapi import Request
@app.middleware("http")
async def some_middleware(request: Request, call_next):
response = await call_next(request)
# read API credits for this request
print(request.state.api_credits)
return response
@app.post("/")
async def main(request: Request):
# set api credits for this request
request.state.api_credits = 5
return {"message": "ok"}