Google 应用程序脚本:urlfetchapp - 服务调用次数过多

Posted

技术标签:

【中文标题】Google 应用程序脚本:urlfetchapp - 服务调用次数过多【英文标题】:Google apps script: urlfetchapp - service invoked too many times 【发布时间】:2012-05-15 09:49:21 【问题描述】:

我有一个谷歌电子表格,它在许多单元格中调用用户特定的功能。此函数获取 3-4 个特定的相对较短的网页并对其进行解析。页面每天只更改一次,但我不能/不知道如何强制我的电子表格每天只获取每个页面一次并使用缓存副本。 我相信在 ~20 获取后刷新期间会发生 urlfetchapp 错误。 “服务调用次数过多”。

我尝试找到解决此问题的方法。我认为这个错误的发生是因为许多 URL-fetches(即使对于相同的 URL,内容不变),而不是因为许多解析。

如果是这样,如何减少获取次数?例如,我可以在某处下载页面并在本地解析它们吗?我可以对谷歌电子表格中的网页使用某种缓存吗?如果我将此文件的副本保存在电子表格所在的谷歌驱动器中,它会有帮助吗? 我可以增加 URLfetchapp 的限制吗? 还有其他想法吗?

【问题讨论】:

【参考方案1】:

您应该考虑使用为此类用例创建的Cache service。 This blog post介绍服务展示了一些基本用法。

【讨论】:

谢谢,非常有用的模式。【参考方案2】:

为避免出现类似问题,我实施了一种解决方法。它不是很优雅,但它确实有效。它在循环中使用 Utilities.sleep()

function urlFetchWihtoutError(url) 
  const NB_RETRY = 10;
  var nbSecPause = 1.5;
  var nbErr = 0;
  while (nbErr < NB_RETRY) 
    try 
      if (nbErr > 0) SpreadsheetApp.getActiveSpreadsheet().toast("Here we go again.");
      var res = UrlFetchApp.fetch(url).getContentText();
      return res;
    
    catch (error) 
      nbErr++;
      SpreadsheetApp.getActiveSpreadsheet().toast("Let's pause the system during " + nbSecPause + " seconds. Loop number: " + nbErr);
      Utilities.sleep(nbSecPause * 1000)
      nbSecPause += 0.5;
    
  

【讨论】:

【参考方案3】:

添加缓存正是我所需要的。所以我实现了一个使用缓存的函数 fetch(url),这样可以避免复制调用。

function fetch(url) 
  var cache = CacheService.getScriptCache();
  var result = cache.get(url);
  if(!result) 
    var response = UrlFetchApp.fetch(url);
    result = response.getContentText();
    cache.put(url, result, 21600);
  
  return result;

【讨论】:

以上是关于Google 应用程序脚本:urlfetchapp - 服务调用次数过多的主要内容,如果未能解决你的问题,请参考以下文章