python - 提高进行许多 api 调用并将所有数据存储到一个数据帧中的代码的速度
问题描述
我编写了一个代码,它获取标识符号并向特定 API 发出请求,并返回与此标识符号相关的数据。代码通过数据框运行并获取标识符编号(大约 600)并返回相关信息并转换为 pandas 数据框。最后,将所有数据帧连接成一个数据帧。代码运行速度超级慢。有什么方法可以让它更快。我对 python 没有信心,如果您能分享解决方案代码,我将不胜感激。代码:
file = dataframe
list_df = []
for index,row in file.iterrows():
url = "https://some_api/?eni_number="+str(row['id'])+"&apikey=some_apikey"
payload={}
headers = {
'Accept': 'application/json'
}
response = requests.request("GET", url, headers=headers, data=payload)
a = json.loads(response.text)
df_index = json_normalize(a, 'vessels')
df_index['eni_number'] = row['id']
list_df.append(df_index)
#print(df_index)
total = pd.concat(list_df)
解决方案
这里的瓶颈似乎是 HTTP 请求一个接一个地同步执行。所以大部分时间都浪费在等待服务器的响应上。
使用异步方法可能会获得更好的结果,例如使用grequests并行执行所有 HTTP 请求:
import grequests
ids = dataframe["id"].to_list()
urls = [f"https://some_api/?eni_number={id}&apikey=some_apikey" for id in ids]
payload = {}
headers = {'Accept': 'application/json'}
requests = (grequests.get(url, headers=headers, data=payload) for url in urls)
responses = grequests.map(requests) # execute all requests in parallel
list_df = []
for id, response in zip(ids, responses):
a = json.loads(response.text)
df_index = json_normalize(a, 'vessels')
df_index['eni_number'] = id
list_df.append(df_index)
total = pd.concat(list_df)
推荐阅读
- html - 倾斜 div 容器上的文本溢出
- listview - 将按钮绑定到列表视图数据模板中的命令
- javascript - 如何在 pos 中关闭屏幕时添加弹出动作
- php - 登录 PHP 后登录不重定向到管理索引页面
- matlab - MATLAB 中的谢尔宾斯基三角形
- spring-jdbc - JdbcTemplate 对多个表同时批量更新
- php - Laravel 中所有控制器的通用文件上传
- html - django使用html模板将数据插入数据库
- python - 像“The LJ Speech Dataset”这样的数据集
- python - 为了使用 Python 从 Rust 程序内部调用函数,最佳实践是什么?