编辑:
我发现了问题,但不知道为什么会这样。无论何时我查询: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
在我的根dir:/__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", "*"
部件。
发布于 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
https://stackoverflow.com/questions/70351360
复制相似问题