2016-09-21 91 views
0

我想通过它的API将数据从这里写入Google表格(http://acleddata.com/api/acled/read)。我使用gspread包来提供帮助。写入谷歌电子表格API非常慢

下面是代码:

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表格,但速度慢得不可思议。花了40分钟写了一百行,然后我打断了剧本。

我能做些什么来加速这个过程吗?

谢谢!

回答

1

根据您的代码,您使用的是旧版本V3 Google Data API。为了获得更好的性能,请切换到V4 API。迁移指南可用here

+0

感谢您的回复。我检查了这一点。与此同时,我想出了什么可能是主要原因 - 使用append_row方法每次调用api时都会调用它。我张贴在下面找到的修复 – Aschharwood

0

这里是更快的解决方案:

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调用。

1

从这个thread基础,谷歌电子表格API可以取决于许多因素,包括您的连接速度,以谷歌的服务器,代理服务器的使用等,避免其gspread.login一个循环中,因为这种方法速度慢是很慢。

... get_all_records来救我了,比整张纸的范围快得多。

我也看到在这个forum,它依赖于工作表的大小,从而排在工作表中增加,程序运行更慢。