FastAPI测试客户端是帖子或放置时的请求重定向
我正在为FastAPI应用程序编写测试。当我用get方法编写端点测试时,一切都按预期工作,但是当我用邮政方法调用端点时,我的请求将重定向到 http:// testserver 是我终点的一个示例:
from json import JSONDecodeError
from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_400_BAD_REQUEST
router = APIRouter()
@router.post("/test")
async def test(
request: Request,
):
try:
body = await request.json()
except JSONDecodeError:
return JSONResponse(content={}, status_code=HTTP_400_BAD_REQUEST)
return JSONResponse(content=body)
这是我的测试的一个示例:
from starlette.testclient import TestClient
from app import app
client = TestClient(app)
def test_cookies():
res = client.post(
"api/test/",
json={
"name": "test"
},
)
assert 200 == res.status_code
同样,这只是在帖子中发生并提出请求get请求的工作正常。知道为什么会发生这种情况?
I'm writing test for a FastAPI application. When I write test for an endpoint with GET method everything works as expected, but when I call an endpoint with POST method somehow my request gets redirected to http://testserver this is an example of my endpoints:
from json import JSONDecodeError
from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_400_BAD_REQUEST
router = APIRouter()
@router.post("/test")
async def test(
request: Request,
):
try:
body = await request.json()
except JSONDecodeError:
return JSONResponse(content={}, status_code=HTTP_400_BAD_REQUEST)
return JSONResponse(content=body)
and this is an example of my test:
from starlette.testclient import TestClient
from app import app
client = TestClient(app)
def test_cookies():
res = client.post(
"api/test/",
json={
"name": "test"
},
)
assert 200 == res.status_code
again this happens just with POST and PUT requests the GET request works just fine. any idea why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的端点注册为
/api/test
,当您调用/api/test/code>时 - 注意落后斜线的差异。
默认情况下,FastApi将发布重定向,以使您的浏览器与正确的端点交谈。您看到的
http:// testserver
url是TestClient中使用的内部主机名。Your endpoint is registered as
/api/test
, while you're calling/api/test/
- notice the difference in the trailing slash.By default FastAPI will issue a redirect to make your browser talk to the correct endpoint. The
http://testserver
URL you're seeing is the internal hostname used in the TestClient.