FastAPI测试客户端是帖子或放置时的请求重定向

发布于 2025-02-12 14:34:53 字数 1046 浏览 0 评论 0原文

我正在为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失眠症患者 2025-02-19 14:34:53

您的端点注册为/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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文