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

Cloud Run requests triggers error 400 without reaching deployed service

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

我使用 FastAPI, the Location model is based on Pydantic's BaseModel 在 python3 上创建了 API。

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

class Location(BaseModel):
    lat: float
    lng: float


@router.get('/test_404')
async def test_404(origin: Location = Body(...),
                   destination: Location = Body(...)):
    print(origin)
    print(destination)
    return {'res': 'ok'}

路由应该在请求的正文中包含两个参数:起点和终点,它 确实 但只有当我在本地部署它时. 这 :

url_local = "http://0.0.0.0:8080/test_404"
data = {
    'origin': {'lat': 104, 'lng': 342},
    'destination': {'lat': 104, 'lng': 342}
}
resp = requests.get(url_local, json = data)
print(resp.text)

输出:

'{"res":"ok"}'

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

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

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

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

非常感谢

可能与this post, where a user experiences a similar message. After some reading, and seeing your example, I think the solution lies in the REST best practices有关。

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

一些 API 包装器(如 Cloud 运行)可能不接受这种行为,而在您的本地测试中它似乎可以工作。其他 API 包装器可能只接受带有 GET 请求的正文。我建议坚持 REST 最佳实践,你没问题。