1

编辑:

我发现了问题,但不确定为什么会发生这种情况。每当我查询时:最后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

pytest 返回:

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

test_main.py:24: AssertionError

在我的根目录中:/__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'

/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"

/Dockerfile

CMD ["uvicorn", "abm:abm", "--reload", "--proxy-headers", "--host", "0.0.0.0", "--port", "4001", "--forwarded-allow-ips", "*", "--log-level", "debug"]

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

4

1 回答 1

3

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

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

于 2021-12-14T18:40:07.873 回答