我有一個無法解決的問題。我有一個使用 FastAPI 構建的 API 服務,當我嘗試從本地機器上的另一個 Python 腳本呼叫任何端點時,回應需要 2 秒以上。當我通過 cURL 或內置 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 從測驗腳本中呼叫它。我也試過請求包,結果是一樣的。
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 秒后執行。
我試圖檢查請求以查看請求中是否有任何標題或類似內容可能會減慢它的速度,但沒有。當我再次嘗試使用 HTTPX 生成的標頭時,它仍然執行得很快:
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 以及它如何運行應用程式有關,但我不知道為什么。
uj5u.com熱心網友回復:
嘗試使用“127.0.0.1”而不是“localhost”來指代你的機器。我曾經遇到過類似的問題,Windows 上對 localhost 的 DNS 查找需要半秒或更長時間。我對這種行為沒有任何解釋,但至少SO 上的另一個人似乎也為此而苦苦掙扎……
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367975.html
上一篇:如何在訓練模型時修復記憶體錯誤?
下一篇:使用既定規則隨機化串列
