为什么客户端收到的 status_code 与发送的不同?

问题描述 投票:0回答:1

我的 API 中有这个端点,它调用另一个 API 中的另一个端点。我只是将收到的回复返回给客户,但有时客户实际上收到的

status_code
与我在
return
声明中传递的不同。

我正在做这样的事情(使用 FastAPI):

@router.post("/my_endpoint")
async def my_method():
    ...
    response = requests.post(url=<url_to_the_other_api>, headers=headers, timeout=10)
    return response.json()

客户端有时会收到一条错误消息,但仍然是

status_code
200。我以为我返回的是相同的接收到的响应对象,但显然不是。

有人可以解释一下吗?

我认为

json()
方法或 FastAPI 可以创建一个新的
response
对象并只使用旧的主体。是这样吗?这种行为对我来说很不清楚。

python python-requests fastapi http-status-codes starlette
1个回答
0
投票

使用

return response.json()
时,您只是将
response
的内容返回给
requests
的 Python
<the_other_api>
发出的请求。然后,FastAPI 在幕后将 JSON 数据放入
JSONResponse
中,并使用
status_code
200
将其返回给客户端(有关详细信息,请参见 this answer)。

如果您想使用

status_code
的响应中返回的
media_type
(以及
content-type
/
<the_other_api>
),您可以 直接返回自定义响应

例子

from fastapi import FastAPI, Response
import requests

app = FastAPI()

@app.get('/')
def root():
    # returns 400 Error Not Found Response (for testing purposes)
    #r = requests.get(url='http://httpbin.org/NotValidRoute')
    
    # reurns 200 Successful Response
    r = requests.get(url='http://httpbin.org/json')
    
    return Response(content=r.content, media_type=r.headers['content-type'], status_code=r.status_code)

但是,我会 强烈建议 使用

httpx
库而不是
requests
httpx
requests
的语法非常相似,易于使用并提供
async
支持),如图所示在这个答案,以及这里这里。如果您想继续使用
requests
,请确保使用正常
def
定义端点(如上面的示例所示)not
async def
(如您的问题所示)-看看this回答有关原因的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.