简体   繁体   English

当 status_code = 200 时重试 python 请求

[英]retry with python requests when status_code = 200

The API I'm sending requests to has a bit of an unusual format for its responses我向其发送请求的 API 的响应格式有点不寻常

  1. It always returns status_code = 200它总是返回status_code = 200

  2. There's an additional error key inside the returned json that details the actual status of the response:返回的 json 中有一个额外的error键,详细说明了响应的实际状态:

    2.1. 2.1. error = 0 means it successfully completes error = 0表示成功完成

    2.2. 2.2. error != 0 means something went wrong error != 0表示出现问题

I'm trying use the Retry class in urlib3 , but so far I understand it only uses the status_code from the response, not its actual content.我正在尝试在urlib3使用 Retry 类,但到目前为止我知道它只使用响应中的status_code ,而不是它的实际内容。

Are there any other options?还有其他选择吗?

I think you're going to have to use a 'hybrid' approach here and manually do a retry after analysis.我认为您将不得不在这里使用“混合”方法,并在分析后手动重试。

If I'm hearing you right, the API always returns status_code 200 even if your request is bad.如果我status_code错的话,即使您的请求不好,API 也总是返回status_code 200。 So we need to handle two cases, and write our own Retry handler(s).所以我们需要处理两种情况,并编写我们自己的重试处理程序。 You might try something like this approach, which also takes into account the number of requests you're making to determine if there's a repeated error case.您可以尝试类似这种方法,该方法还会考虑您发出的请求数量,以确定是否存在重复错误情况。

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