python请求随JSONDecodeError随机中断

mat*_*cam 5 python json python-requests jsondecoder

我已经调试了几个小时,为什么我的代码随机因此错误而中断: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是我的代码:

while True:
    try:
        submissions = requests.get('http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since).json()['submission']['records']
        break
    except requests.exceptions.ConnectionError:
        time.sleep(100)
Run Code Online (Sandbox Code Playgroud)

而且我一直在通过打印进行调试,requests.get(url)并且requests.get(url).text遇到了以下“特殊”情况:

  1. requests.get(url)返回成功的200响应并requests.get(url).text返回html。我已经在线阅读了使用时应该会失败的信息requests.get(url).json(),因为它无法读取html,但是以某种方式不会损坏。为什么是这样?

  2. requests.get(url)返回成功的200响应,并且requests.get(url).text为json格式。我不明白为什么到requests.get(url).json()JSONDecodeError时会中断?

requests.get(url).text情况2 的确切值为:

{
  "submission": {
    "columns": [
      "pk",
      "form",
      "date",
      "ip"
    ],
    "records": [
      [
        "21197",
        "mistico-form-contacto-form",
        "2018-09-21 09:04:41",
        "186.179.71.106"
      ]
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*ody 9

查看此 API的文档,似乎唯一的响应是 JSON 格式,因此接收 HTML 很奇怪。要增加接收 JSON 响应的可能性,您可以将“接受”标头设置为“应用程序/json”。

我尝试多次使用参数查询此 API,但没有遇到JSONDecodeError. 这个错误很可能是服务器端另一个错误的结果。为了处理它,except一个json.decoder.JSONDecodeError除了ConnectionError错误您目前except并在相同的方式处理此错误ConnectionError

这是一个考虑到所有这些的例子:

import requests, json, time, random

def get_submission_records(client, since, try_number=1):
    url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since
    headers = {'Accept': 'application/json'}
    try:
        response = requests.get(url, headers=headers).json()
    except (requests.exceptions.ConnectionError, json.decoder.JSONDecodeError):
        time.sleep(2**try_number + random.random()*0.01) #exponential backoff
        return get_submission_records(client, since, try_number=try_number+1)
    else:
        return response['submission']['records']
Run Code Online (Sandbox Code Playgroud)

我还将这个逻辑包装在一个递归函数中,而不是使用while循环,因为我认为它在语义上更清晰。此函数还在使用指数退避(每次失败后等待两倍的时间)再次尝试之前等待。

编辑:对于 Python 2.7,尝试解析错误 json 的错误是 a ValueError,而不是 aJSONDecodeError

import requests, time, random

def get_submission_records(client, since, try_number=1):
    url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since
    headers = {'Accept': 'application/json'}
    try:
        response = requests.get(url, headers=headers).json()
    except (requests.exceptions.ConnectionError, ValueError):
        time.sleep(2**try_number + random.random()*0.01) #exponential backoff
        return get_submission_records(client, since, try_number=try_number+1)
    else:
        return response['submission']['records']
Run Code Online (Sandbox Code Playgroud)

所以只需将该except行更改为包含一个ValueError而不是json.decoder.JSONDecodeError.