首页 > 解决方案 > 在 python 3 中获取 REST API 服务器响应时间

问题描述

我正在尝试在 python 3 中获取服务器响应时间

我试过这段代码 -

    api_url = "https://example.com?id=12345"
    api_header = {'Authorization': 'Bearer ' + access_token}
    api_response = requests.get(api_url, headers=api_header)
    response_time = api_response.elapsed
    print(response_time)

但它返回的“经过时间”远高于服务器响应时间。

当我从 Postman 查询相同的 api 时,它显示的响应时间约为 250 毫秒。但是上面的代码显示了850ms的经过时间。

有没有办法在 python 3 中获得实际的服务器响应时间?

标签: pythonpython-3.x

解决方案


您可以尝试使用该datetime模块。通过将之前和之后的时间存储为变量,您可以计算出它们之间的差异,从而计算出进行调用所花费的时间。

import datetime as dt


api_url = "https://example.com?id=12345"
api_header = {'Authorization': 'Bearer ' + access_token}

start = dt.datetime.now()
api_response = requests.get(api_url, headers=api_header)
end = dt.datetime.now()

time_delta = end - start
response_time = time_delta.total_seconds()

print(response_time)

如果这不能满足您的要求,我建议您查看timeit模块。


推荐阅读