通过其他 Python 应用程序调用时 FastAPI 响应缓慢,但在 cURL 中响应速度很快

FastAPI responding slowly when calling through other Python app, but fast in cURL

我有一个问题无法解决。我有一个使用 FastAPI 构建的 API 服务,当我尝试从本地计算机上的另一个 Python 脚本调用任何端点时,响应需要 2 秒以上。当我通过 cURL 或 built-in Swagger 文档发送相同的请求时,响应几乎是即时的。

整个服务器脚本是这样的:

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8000)

然后我使用 HTTPX 从测试脚本调用它。我也试过requests包,也是一样的结果

import httpx
r = httpx.get('http://localhost:8000/')
print(r.elapsed)

这会打印出如下内容:0:00:02.069705

然后我使用 cURL 做同样的事情:

curl -w "@curl-format.txt" -o /dev/null -X 'GET' 'http://localhost:8000/'

这会打印:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    32  100    32    0     0    941      0 --:--:-- --:--:-- --:--:--   969
     time_namelookup:  0.006436s
        time_connect:  0.006747s
     time_appconnect:  0.000000s
    time_pretransfer:  0.006788s
       time_redirect:  0.000000s
  time_starttransfer:  0.034037s
                     ----------
          time_total:  0.034093s

问题不是端点做了什么,而是它甚至没有开始执行 2 秒。我在端点上有一个调试器 运行,第一行仅在 2 秒后执行。

我试图检查请求以查看请求中是否有任何 headers 或类似的东西可以减慢它的速度,但没有。当我再次尝试使用 HTTPX 生成的 headers 时,它仍然执行得很快:

curl -w "@curl-format.txt" -o /dev/null -X 'GET' \
  'http://localhost:8000/events' \
  -H 'accept: */*' \
  -H 'host: localhost:8000' \
  -H 'accept-encoding: gzip, deflate' \
  -H 'connection: keep-alive' \
  -H 'user-agent: python-httpx/0.20.0'

这里是PyCharm中请求的截图,遗憾的是不能直接转储到JSON。

我开始认为它与 Uvicorn 及其运行应用程序的方式有关,但我不明白为什么。

尝试使用“127.0.0.1”而不是“localhost”来引用您的机器。我曾经遇到过类似的问题,在 windows 上对本地主机的 DNS 查找需要半秒或更长时间。我没有对这种行为的解释,但至少 one other person 在 SO 上似乎也在为此苦苦挣扎......