【问题标题】:Cloud Functions with Requests return 'Could not parse JSON' error带有请求的云函数返回“无法解析 JSON”错误
【发布时间】:2022-01-06 18:21:49
【问题描述】:

我正在 python 中运行云函数以从 api 返回一些数据。该函数未执行,出现错误{'code': 400, 'message': 'Could not parse JSON'}

这是我的代码:

import requests
import json

def my_function(request):

    url = 'https://blablabla/detailed'
    headers = {'X-Api-Key': 'XXXXXXXX',
           'content-type': 'application/json'}

    data = '{"dateRangeStart":"2020-05-10T00:00:00.000","dateRangeEnd":"2020-05-16T23:59:59.000","amountShown": "HIDE_AMOUNT","detailedFilter":{ "page":"1","pageSize":"50"}}'
    
    #req = requests.post(url, headers=headers, json=data)
    req = requests.post(url, headers=headers, data=json.dumps(data))
    print(req.json())

我应该如何格式化我的数据变量?

【问题讨论】:

标签: python-3.x python-requests google-cloud-functions


【解决方案1】:

只需将您的 dict 作为您的 json 参数,您无需指定 content-type 标头 requests 将为您完成。

import requests


def my_function(request):
    url = 'https://blablabla/detailed'
    headers = {'X-Api-Key': 'XXXXXXXX', }

    data = {"dateRangeStart": "2020-05-10T00:00:00.000", "dateRangeEnd": "2020-05-16T23:59:59.000", "amountShown": "HIDE_AMOUNT", "detailedFilter": { "page": "1", "pageSize": "50", }, }
    
    req = requests.post(url, headers=headers, json=data)
    print(req.json())

如果您没有设置content-type 标头,将尝试为您设置:

  • 使用关键字参数json时:将其设置为application/json
  • 当使用关键字参数data(并且传递的值符合一些标准,大多数时候你不必担心):它会将它设置为application/x-www-form-urlencoded
  • 如果两个 kwargs 都存在 data 优先考虑标题,因此它将被设置为 application/x-www-form-urlencoded

我没有详细说明使用 kwarg files 时的行为,因为它真的很长并且超出了这里的范围。

Here's the source code.

【讨论】:

  • 你能添加更多关于内容类型的解释吗?当你指定它时,在这种情况下会发生什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 2014-05-12
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
相关资源
最近更新 更多