![](/img/trans.png)
[英]FastAPI POST Pydantic method unit testing redirecting status_code 307 instead of 200
[英]Keep getting "307 Temporary Redirect" before returning status 200 hosted on FastAPI + uvicorn + Docker app - how to return status 200?
編輯:
我發現了問題,但不確定為什么會發生這種情況。 每當我查詢: http://localhost:4001/hello/
最后帶有“ /
” - 我得到正確的 200 狀態響應。 我不懂為什么。
原帖:
每當我向我的應用程序發送查詢時 - 我不斷收到 307 重定向。 如何讓我的應用程序返回常規狀態 200 而不是通過 307 重定向它
這是請求 output:
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", "*"
部分。
發生這種情況是因為您為視圖定義的確切路徑是yourdomainname/hello/
,所以當您在最后沒有/
的情況下點擊它時,它首先嘗試到達該路徑,但由於它不可用,它在附加/
后再次檢查給出重定向status code 307
,然后當它找到實際路徑時,它返回在與該路徑鏈接的function/view
中定義的狀態代碼,即在您的情況下status code 200
。
您還可以在此處閱讀有關此問題的更多信息: https://github.com/tiangolo/fastapi/issues/2060#issuecomment-834868906
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.