FastAPI 引发缺少位置参数错误

FastAPI Raises Missing Positional Argument Error

以下代码引发以下异常。

我不确定我是否完全理解 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 不知道如何处理传递的这些参数中的多个,因此您无法混合搭配。理想情况下,我能够获取 RequestHeader 对象并将它们传递给后台任务进行处理。

装饰器 @app.route 似乎是问题所在。 (参见:https://github.com/tiangolo/fastapi/issues/912)使用 @app.api_route 代替甚至更好 @app.get@app.post.