gpt4 book ai didi

fastapi - 如何从 FastAPI 全局依赖项获取返回值

转载 作者:行者123 更新时间:2023-12-05 09:31:21 28 4
gpt4 key购买 nike

快速API 0.68.0

python 3.8

from fastapi import Depends, FastAPI, Header, HTTPException


async def verify_key(x_key: str = Header(...)):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
return x_key



app = FastAPI(dependencies=[Depends(verify_key)])



@app.get("/items/")
async def read_items():

return [{"item": "Portal Gun"}, {"item": "Plumbus"}]


这是FastAPI文档中的一个例子(省略部分代码)

有没有办法在read_items()中得到x_key

最佳答案

from fastapi import Request, Depends

async def verify_key(request: Request, x_key: str = Header(...)):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")

# save x_key
request.state.x_key = x_key
return x_key


app = FastAPI(dependencies=[Depends(verify_key)])


@app.get("/items/")
async def read_items(request: Request):
# get 'x_key' from request.state
x_key = request.state.x_key
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]

flask /瓶子模拟

# current_request.py
import contextvars
from fastapi import Request

_CURRENT_REQUEST = contextvars.ContextVar("_CURRENT_REQUEST", default=None)

class CurrentRequest:

def __getattr__(self, a):
current_request = _CURRENT_REQUEST.get()
if current_request is None:
raise RuntimeError('Out of context')
return getattr(current_request, a)

request: Request = CurrentRequest()

async def set_current_request(request: Request):
_CURRENT_REQUEST.set(request)


# fastapi app/subroute
from fastapi import Request, Depends

from .current_request import request, set_current_request


async def verify_key(x_key: str = Header(...)):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")

# save x_key
request.state.x_key = x_key
return x_key


# ! set_current_request should go first
app = FastAPI(dependencies=[Depends(set_current_request), Depends(verify_key)])


@app.get("/items/")
async def read_items():
# get 'x_key' from request.state
x_key = request.state.x_key
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]

关于fastapi - 如何从 FastAPI 全局依赖项获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68827065/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com