首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在返回FastAPI + uvicorn + Docker应用程序上托管的状态200之前,继续获得"307临时重定向“--如何返回状态200?

在返回FastAPI + uvicorn + Docker应用程序上托管的状态200之前,继续获得"307临时重定向“--如何返回状态200?
EN

Stack Overflow用户
提问于 2021-12-14 15:25:31
回答 1查看 10.5K关注 0票数 13

编辑:

我发现了问题,但不知道为什么会这样。无论何时我查询:http://localhost:4001/hello/,最后带有"/“--我得到一个正确的200状态响应。我不明白为什么。

原文:

每当我发送一个查询到我的应用程序-我不断得到307重定向。如何使我的应用程序返回常规状态200而不是通过307重定向

这是请求输出:

代码语言:javascript
运行
复制
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返回:

代码语言:javascript
运行
复制
E       assert 307 == 200
E        +  where 307 = <Response [307]>.status_code

test_main.py:24: AssertionError

在我的根dir:/__init__.py文件中:

代码语言:javascript
运行
复制
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文件:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
CMD ["uvicorn", "abm:abm", "--reload", "--proxy-headers", "--host", "0.0.0.0", "--port", "4001", "--forwarded-allow-ips", "*", "--log-level", "debug"]

我试着用和不带"--forwarded-allow-ips", "*"部件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-14 18:40:07

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

您还可以在这里阅读更多关于这个问题的内容:https://github.com/tiangolo/fastapi/issues/2060#issuecomment-834868906

票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70351360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档