【发布时间】:2021-05-31 16:45:38
【问题描述】:
以下代码引发以下异常。
我不确定我是否完全了解 FastAPI 的工作原理。有人可以帮我理解吗?
from fastapi import FastAPI
from fastapi import BackgroundTasks
from fastapi import Request
app = FastAPI()
async def parse_request(req: Request):
print(req)
print(req.client.host)
@app.route("/endpoint")
async def endpoint(request: Request, background_tasks: BackgroundTasks):
background_tasks.add_task(parse_request, request)
return {"msg": "ok"}
例外:
Traceback (most recent call last):
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/routing.py", line 241, in handle
await self.app(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/routing.py", line 52, in app
response = await func(request)
TypeError: endpoint() missing 1 required positional argument: 'background_tasks'
当我在路由路径中传入我自己的变量时,我已经在没有 Request 参数的情况下工作了:
@app.get("/test/{input_str}")
async def test(input_str: str, background_tasks: BackgroundTasks):
background_tasks.add_task(do_stuff, input_str)
return {"Hello": "World"}
似乎 Starlette 不知道如何处理多个传递的这些参数,因此您无法混搭。理想情况下,我可以获取Request 和Header 对象并将它们传递给后台任务进行处理。
【问题讨论】:
标签: python-3.x fastapi python-3.9