【问题标题】:Translate Python request to an Apps Script request将 Python 请求转换为 Apps 脚本请求
【发布时间】:2021-04-15 00:45:41
【问题描述】:

我正在尝试使用 Apps 脚本将 API 请求自动化到 Google 电子表格中,GET 请求似乎在 python 中工作正常,但是当我尝试使用 UrlFetchApp.fetch 方法复制相同的请求时,它会引发 422 错误,忽略显然是标题。

这里是工作 python 代码:

url = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token={}".format(token)
r = requests.get(url = caixa, params= {'data_inicio' : '2018-01-01',
                                       'data_fim' : '2022-02-01', 
                                       'regime':'caixa'})

但当我尝试将其复制到 Apps 脚本时,它似乎忽略了这些参数

var link = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token=my_access_token";

headers = {
'data_inicio': '2020-01-01',
'data_fim': '2020-06-30',
'regime': 'caixa',
};


var options = {
  "method" : "get",
  "contentType":"application/json",
  'headers': headers,
    };
  Logger.log(options);
  var res = UrlFetchApp.fetch(link, options)

它会抛出以下错误消息:

Exception: Request failed for https://api.granatum.com.br returned code 422. Truncated server response: {"errors":{"data_inicio":["é obrigatório"],"data_fim":["é obrigatório"],"regime":["é obrigatório","inválido"]}} (use muteHttpExceptions option to examine full response)

翻译响应,它要求上面通知的这三个参数,就好像它没有收到它们一样。

【问题讨论】:

    标签: python google-apps-script httprequest urlfetch


    【解决方案1】:

    我相信你的目标如下。

    • 您希望将以下 python 脚本转换为 Google Apps 脚本。

        url = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token={}".format(token)
        r = requests.get(url = caixa, params= {'data_inicio' : '2018-01-01', 'data_fim' : '2022-02-01', 'regime':'caixa'})
      
      • 在此脚本中,url"https://api.granatum.com.br/v1/relatorios/fluxo_caixa?access_token={}".format(token)。但是requests 使用url = caixa。但是,根据您的 Google Apps 脚本,在这个答案中,它假设您使用的是url

    当你想在上面的脚本中使用url时,下面的修改如何?

    修改点:

    • 当我看到你的 python 脚本时,params 的值似乎是作为查询参数发送的。但在您的脚本中,这些值是在请求标头中发送的。
    • 而且,在 GET 方法的情况下,不需要使用内容类型。

    当以上几点反映到 Google Apps Script 时,它变成如下。

    修改脚本:

    function myFunction() {
      // This is from https://gist.github.com/tanaikech/70503e0ea6998083fcb05c6d2a857107
      String.prototype.addQuery = function(obj) {
        return this + Object.keys(obj).reduce(function(p, e, i) {
          return p + (i == 0 ? "?" : "&") +
            (Array.isArray(obj[e]) ? obj[e].reduce(function(str, f, j) {
              return str + e + "=" + encodeURIComponent(f) + (j != obj[e].length - 1 ? "&" : "")
            },"") : e + "=" + encodeURIComponent(obj[e]));
        },"");
      }
    
      var url = "https://api.granatum.com.br/v1/relatorios/fluxo_caixa";
      var query = {
        'data_inicio': '2020-01-01',
        'data_fim': '2020-06-30',
        'regime': 'caixa',
        'access_token': 'my_access_token'
      };
      var res = UrlFetchApp.fetch(url.addQuery(query));
      Logger.log(res.getContentText());
    }
    

    注意:

    • 在这个答案中,它假定您的 python 脚本可以与 url 一起正常工作。并且,它假设可以使用您的访问令牌。请注意这一点。

    参考:

    【讨论】:

    • 嗨!有效!响应是预期的 JS 对象!谢谢!你能解释一下 String.prototype.addQuery 部分吗?我对 Apps 脚本还很陌生,当然想了解它!再次感谢您!
    • @João Rafael Borowski Tedeschi 感谢您的回复。我很高兴你的问题得到了解决。关于String.prototype.addQuery,该函数用于将JSON对象转换为查询参数。因为在 Google Apps Script 中,没有准备这种方法。此外,您可以手动添加 JSON 对象作为查询参数,例如 https://api.granatum.com.br/v1/relatorios/fluxo_caixa?data_inicio=2020-01-01&data_fim=2020-06-30&regime=caixa&access_token=my_access_token。如果这个解释不是你想要的,我很抱歉。
    猜你喜欢
    • 2020-08-31
    • 2021-06-30
    • 1970-01-01
    • 2023-04-02
    • 2018-05-14
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多