在返回 FastAPI + uvicorn + Docker 应用程序上托管的状态 200 之前,不断收到“307 临时重定向” - 如何返回状态 200?

Ric*_*hez 45 python redirect http-status-code-307 fastapi

编辑:

我发现了问题,但不确定为什么会发生这种情况。每当我查询:最后http://localhost:4001/hello/带有“ ”时 - 我都会得到正确的 200 状态响应。/我不懂为什么。

原帖:

每当我向我的应用程序发送查询时,我都会收到 307 重定向。如何让我的应用返回常规状态 200,而不是通过 307 重定向

这是请求输出:

abm                  | INFO:     172.18.0.1:46476 - "POST /hello HTTP/1.1" 307 Temporary Redirect
abm                  | returns the apples data. nothing special here.
abm                  | INFO:     172.18.0.1:46480 - "POST /hello/ HTTP/1.1" 200 OK
Run Code Online (Sandbox Code Playgroud)

pytest 返回:

E       assert 307 == 200
E        +  where 307 = <Response [307]>.status_code

test_main.py:24: AssertionError
Run Code Online (Sandbox Code Playgroud)

在我的根目录:/__init__.py文件:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# from .configs import cors
from .subapp import router_hello
from .potato import router_potato
from .apple import router_apple


abm = FastAPI(
    title = "ABM"
)

# potato.add_middleware(cors)
abm.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

abm.include_router(router_hello.router)
abm.include_router(router_potato.router)
abm.include_router(router_apple.router)

@abm.post("/test", status_code = 200)
def test():
    print('test')
    return 'test'
Run Code Online (Sandbox Code Playgroud)

/subapp/router_hello.py文件:

router = APIRouter(
    prefix='/hello',
    tags=['hello'],
)

@router.post("/", status_code = 200)
def hello(req: helloBase, apple: appleHeader = Depends(set_apple_header), db: Session = Depends(get_db)) -> helloResponse:
    db_apple = apple_create(apple, db, req.name)
    if db_apple:
        return set_hello_res(db_apple.potato.api, db_apple.name, 1)
    else:
        return "null"
Run Code Online (Sandbox Code Playgroud)

/Dockerfile

CMD ["uvicorn", "abm:abm", "--reload", "--proxy-headers", "--host", "0.0.0.0", "--port", "4001", "--forwarded-allow-ips", "*", "--log-level", "debug"]
Run Code Online (Sandbox Code Playgroud)

我尝试过有部分和没有"--forwarded-allow-ips", "*"部分。

Kau*_*rma 89

发生这种情况是因为您为视图定义的确切路径是 yourdomainname/hello/,所以当您最后没有点击它时/,它首先尝试到达该路径,但由于它不可用,它会在附加后再次检查/并给出重定向status code 307,然后当它找到实际路径,它返回与function/view该路径链接中定义的状态代码,即status code 200在您的情况下。

您还可以在此处阅读有关该问题的更多信息: https: //github.com/tiangolo/fastapi/issues/2060#issuecomment-834868906

  • +1。由于一些奇怪的原因,当我在本地测试我的 API 时,一切都很好,但是当部署到 AWS Lambda 时,我得到了无限的重定向。谢谢! (5认同)