我将request
对象作为类级依赖项,如图所示,以便能够在类中的所有路由中使用它。问题是,然而,当我试图访问请求体-它错误与Stream consumed
错误。
示例代码:
from fastapi import File, Request, UploadFile
from fastapi_utils.inferring_router import InferringRouter
from fastapi_utils.cbv import cbv
app = FastAPI()
router = InferringRouter()
@cbv(router)
class ExampleRouteClass:
request: Request
file: Optional[UploadFile] = File(None)
type: Optional[str] = None
@router.post("/example-route/")
async def example_function(self):
headers = self.request.headers # this works like a charm
data = await self.request.json() # this errors with RuntimeError: Stream consumed
return headers
app.include_router(router)
示例curl
请求:
curl -x POST 'http://example.com:port/example-route'
-H 'secret-key: supersecret'
-d '{"some_data": "data"}'
问题是与UploadFile
-所以作为一个解决方案,我把它放在路由本身,因为它是唯一的路由在类中使用它。
给出现这个错误的人留下这个:
class ExampleRouteClass:
request: Request
type: Optional[str] = None
@router.post("/example-route/")
async def example_function(self, file: Optional[UploadFile] = File(None)):
headers = self.request.headers # this works like a charm
data = await self.request.json() # this works now too
return headers