Cloud Run 请求在未到达已部署服务的情况下触发错误 400

Luk*_*sic 3 python-3.x google-cloud-platform pydantic google-cloud-run fastapi

我目前正在使用Google Cloud Run部署 API,尽管一切正常,但我现在很难理解我收到的错误。

\n

我使用FastAPI在 python3 上创建了 API ,位置模型基于Pydantic\'s BaseModel。

\n

为了说明这一点,我定义了一条测试路线,如下所示:

\n
class Location(BaseModel):\n    lat: float\n    lng: float\n\n\n@router.get(\'/test_404\')\nasync def test_404(origin: Location = Body(...),\n                   destination: Location = Body(...)):\n    print(origin)\n    print(destination)\n    return {\'res\': \'ok\'}\n
Run Code Online (Sandbox Code Playgroud)\n

该路由应在请求正文中采用两个参数:起点和目的地,并且只有当我在本地部署它时才会这样做。\n这:

\n
url_local = "http://0.0.0.0:8080/test_404"\ndata = {\n    \'origin\': {\'lat\': 104, \'lng\': 342},\n    \'destination\': {\'lat\': 104, \'lng\': 342}\n}\nresp = requests.get(url_local, json = data)\nprint(resp.text)\n
Run Code Online (Sandbox Code Playgroud)\n

输出:

\n
\'{"res":"ok"}\'\n
Run Code Online (Sandbox Code Playgroud)\n

当我在 Cloud Run 上部署相同的服务时,就会出现问题。我的所有其他路线都工作正常,但以下是当我将上面的代码与容器 url 一起使用时得到的输出:

\n
    <!DOCTYPE html>\\n\n    <html lang=en>\n    <meta charset=utf-8>\n    \\n\n    <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">\n    \\n <title>Error 400 (Bad Request)!!1</title>\\n\n    \\n <a href=//www.google.com/><span id=logo aria-label=Google></span></a>\\n\n    <p><b>400.</b>\n        <ins>That\xe2\x80\x99s an error.</ins>\n        \\n\n    <p>Your client has issued a malformed or illegal request.\n        <ins>That\xe2\x80\x99s all we know.</ins>\n
Run Code Online (Sandbox Code Playgroud)\n

这是由谷歌触发的错误,它不会让我的请求到达服务(没有日志条目)

\n

我在网上搜索过但没有找到导致此错误的原因。我缺少什么?

\n

非常感谢

\n

Neb*_*tic 7

它可能与这篇文章有关,其中用户遇到了类似的消息。经过一番阅读并查看您的示例后,我认为解决方案在于 REST 最佳实践

严格来说,GET 请求在执行请求时不应发送任何数据,除了 URI 中包含的任何数据。从技术上讲,一切皆有可能,但您应该使用查询参数而不是发送正文。

某些 API 包装器(例如 Cloud Run)可能不接受此行为,而在您的本地测试中它似乎可以工作。其他 API 包装器可能只接受带有 GET 请求的正文。我建议坚持 REST 最佳实践,这样就可以了。