写入 Google 电子表格 API 极慢
Writing to Google Spreadsheet API Extremely Slow
我正在尝试通过它的 API.I 将数据从这里 (http://acleddata.com/api/acled/read) 写入 Google Sheets,使用 gspread 包来提供帮助。
代码如下:
r = requests.get("http://acleddata.com/api/acled/read")
data = r.json()
data = data['data']
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
for row in data:
sheet.append_row(row.values())
数据是字典列表,每个字典代表电子表格中的一行。这是写给我的 Google Sheet 但速度慢得无法使用。写一百行轻松花了 40 分钟,然后我中断了脚本。
我可以做些什么来加快这个过程吗?
谢谢!
根据您的代码,您使用的是旧版 V3 Google Data API. For better performance, switch to the V4 API. A migration guide is available here。
这是更快的解决方案:
cell_list = sheet.range('A2:'+numberToLetters(num_columns)+str(num_lines+1))
for cell in cell_list:
val = df.iloc[cell.row-2, cell.col-1]
if type(val) is str:
val = val.decode('utf-8')
elif isinstance(val,(int, long, float, complex)):
val= int(round(val))
cell.value = val
sheet.update_cells(cell_list)
这是从这里导出的https://www.dataiku.com/learn/guide/code/python/export-a-dataset-to-google-spreadsheets.html
我相信这里的变化是这个解决方案创建了一个 cell_list 对象,它只需要一个 API 调用。
基于此 thread,Google 电子表格 API 可能会非常慢,具体取决于许多因素,包括您与 Google 服务器的连接速度、代理的使用等. 避免在循环中使用 gspread.login
因为这种方法很慢。
...get_all_records
came to my rescue, much faster than range for entire sheet.
我也在这个 forum 中读到它取决于工作表的大小,因此随着工作表中行的增加,程序 运行 甚至更慢。
我正在尝试通过它的 API.I 将数据从这里 (http://acleddata.com/api/acled/read) 写入 Google Sheets,使用 gspread 包来提供帮助。
代码如下:
r = requests.get("http://acleddata.com/api/acled/read")
data = r.json()
data = data['data']
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
for row in data:
sheet.append_row(row.values())
数据是字典列表,每个字典代表电子表格中的一行。这是写给我的 Google Sheet 但速度慢得无法使用。写一百行轻松花了 40 分钟,然后我中断了脚本。
我可以做些什么来加快这个过程吗?
谢谢!
根据您的代码,您使用的是旧版 V3 Google Data API. For better performance, switch to the V4 API. A migration guide is available here。
这是更快的解决方案:
cell_list = sheet.range('A2:'+numberToLetters(num_columns)+str(num_lines+1))
for cell in cell_list:
val = df.iloc[cell.row-2, cell.col-1]
if type(val) is str:
val = val.decode('utf-8')
elif isinstance(val,(int, long, float, complex)):
val= int(round(val))
cell.value = val
sheet.update_cells(cell_list)
这是从这里导出的https://www.dataiku.com/learn/guide/code/python/export-a-dataset-to-google-spreadsheets.html
我相信这里的变化是这个解决方案创建了一个 cell_list 对象,它只需要一个 API 调用。
基于此 thread,Google 电子表格 API 可能会非常慢,具体取决于许多因素,包括您与 Google 服务器的连接速度、代理的使用等. 避免在循环中使用 gspread.login
因为这种方法很慢。
...
get_all_records
came to my rescue, much faster than range for entire sheet.
我也在这个 forum 中读到它取决于工作表的大小,因此随着工作表中行的增加,程序 运行 甚至更慢。