2016-09-21 106 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,它依賴於工作表的大小,從而排在工作表中增加,程序運行更慢。