【问题标题】:Keep getting "307 Temporary Redirect" before returning status 200 hosted on FastAPI + uvicorn + Docker app - how to return status 200?在返回托管在 FastAPI + uvicorn + Docker 应用程序上的状态 200 之前,不断获得“307 临时重定向” - 如何返回状态 200?
【发布时间】:2022-01-17 21:52:24
【问题描述】:

编辑:

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

【问题讨论】:

    标签: python redirect fastapi http-status-code-307


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2015-10-13
      • 2013-12-26
      • 1970-01-01
      • 2021-12-18
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多