繁体   English   中英

当 status_code = 200 时重试 python 请求

[英]retry with python requests when status_code = 200

我向其发送请求的 API 的响应格式有点不寻常

  1. 它总是返回status_code = 200

  2. 返回的 json 中有一个额外的error键,详细说明了响应的实际状态:

    2.1. error = 0表示成功完成

    2.2. error != 0表示出现问题

我正在尝试在urlib3使用 Retry 类,但到目前为止我知道它只使用响应中的status_code ,而不是它的实际内容。

还有其他选择吗?

我认为您将不得不在这里使用“混合”方法,并在分析后手动重试。

如果我status_code错的话,即使您的请求不好,API 也总是返回status_code 200。 所以我们需要处理两种情况,并编写我们自己的重试处理程序。 您可以尝试类似这种方法,该方法还会考虑您发出的请求数量,以确定是否存在重复错误情况。

import requests
import time
import json


r = None
j = None

attempts = 0

while (attempts < 5):
    # Make request, make sure you have the right data= for payload or json= for
    # JSON payloads in your request.  And repolace `get` with the proper method
    # such as POST or PUT if it's not a GET.
    attempts += 1
    r = requests.get('http://api.example.com/', data=...)
    if r.status_code != 200:
        time.sleep(5)  # Wait between requests for 5 seconds
        continue  # Go back to the beginning of the loop
    else:
        # Decode the bytes in the reply content, then parse it as JSON.
        j = json.loads(r.content.decode('UTF-8'))
        # Check what the output of the 'error' key in the JSON is
        if j['error'] != 0:
            # If there's an error code, then restart the loop and request
            # after a 5 second pause again.
            time.sleep(5)
            continue
        else:
            # If there is no error, simply break the loop, and go on to
            # processing code after it.
            break

if attempts >= 5:
    raise RuntimeError("Consistently invalid or error case returned from API.")


# If there's no error then...
# Do something with the output of `j` which is now a dict containing the parsed
# JSON data.

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM