【问题标题】:Writing to Google Spreadsheet API Extremely Slow写入谷歌电子表格 API 非常慢
【发布时间】:2016-09-21 12:59:10
【问题描述】:

我正在尝试通过其 API 从此处 (http://acleddata.com/api/acled/read) 将数据写入 Google 表格。我正在使用 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 表格,但速度非常慢。写一百行轻松花了 40 分钟,然后我打断了脚本。

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

谢谢!

【问题讨论】:

    标签: python-2.7 google-sheets google-sheets-api gspread


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复。生病检查一下。与此同时,我弄清楚了可能的主要原因是什么——使用这个 append_row 方法每次都会调用 api。生病发布我在下面找到的修复程序
    【解决方案2】:

    这里是更快的解决方案:

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

    【讨论】:

      【解决方案3】:

      基于此thread,Google 电子表格 API 可能会非常慢,这取决于许多因素,包括您与 Google 服务器的连接速度、代理的使用等。避免在循环中使用 gspread.login,因为此方法很慢。

      ...get_all_records 救了我,比整个工作表的范围快得多。

      我还在forum 中读到它取决于工作表的大小,因此随着工作表中行的增加,程序运行得更慢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多