首页 > 解决方案 > 提高进行许多 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)

标签: pythonpandasdataframeapi

解决方案


这里的瓶颈似乎是 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)

推荐阅读