【问题标题】:How to retry an json API request after a timeout using python?如何使用python在超时后重试json API请求?
【发布时间】:2021-03-18 15:25:00
【问题描述】:

我一直在尝试遍历多个 API 请求并解析数据以放入数据帧。运行脚本时,它偶尔会超时,我得到以下输出:{'Message': 'Execution Timeout Expired。在操作完成之前超时时间已过或服务器没有响应。'}。发生这种情况时脚本失败,因为我得到了一个值,因为无法在数据框中输入该值,因此出现以下错误:ValueError: If using all scalar values, you must pass an index 我试过了下面的代码,但我仍然偶尔收到错误。我尝试使用 while 块来检查超时,然后在出现时重试,但不幸的是这不起作用。是否有任何异常处理或其他方式可以处理有时出现的超时错误?

for id in list:
    
        t=0
        x = requests.get('json.api'.format(id)).json()
        print(x)
        while t < 5:
           if 'Timeout' in x:
               "{} json timed out. Trying again".format(id)
               x = requests.get('json.api'.format(id)).json()
               t+=1
           else:
                t = 5
        name = pd.DataFrame( index =[0]).from_dict(x)

【问题讨论】:

  • 网址是否正确?您需要添加http://https://,具体取决于它是否适用。
  • 是的,它工作正常,它可以很好地提取数据,但偶尔会超时,所以脚本只能在部分时间工作。我只是想让它在出现超时消息时重试相同的请求。
  • 您可以使用celery并根据需要配置重试
  • 您介意提供一个例子吗?我对芹菜不太熟悉

标签: python json python-3.x api


【解决方案1】:

给你,你去。

如果你的任务太小,那就有点矫枉过正了,你需要将 RabbitMQ 设置为消息代理。详情请参考Celery Documentation

   (celery_task.py)

   import pandas as pd
   import requests
   from celery import Celery 
   from celery.exceptions import MaxRetriesExceededError, Retry

   app = Celery('tasks', broker='amqp://guest@localhost//')


   @app.task(bind=True, max_retries=100, autoretry_for=(Exception,))
   def loop():
      try:
        """
        do some calc
        """
        for id in list:
            t = 0
            x = requests.get('json.api'.format(id)).json()
            print(x)
            name = pd.DataFrame(index=[0]).from_dict(x)
            """
            do some calc
            """
            
    except MaxRetriesExceededError as max_retry:
        print(max_retry)

触发机制

python
>>> from celery_task import app
>>> app.send_task("tasks.<name your task>", (<enter all the parameterss required to run the task>))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多