簡體   English   中英

如何使用 python 在超時后重試 json API 請求?

[英]How to retry an json API request after a timeout using python?

我一直在嘗試遍歷多個 API 請求並解析數據以放入 dataframe。 運行腳本時,它偶爾會超時,我得到以下 output: {'Message': 'Execution Timeout Expired。 操作完成之前超時時間已過或服務器沒有響應。'} 發生這種情況時腳本失敗,因為我得到一個值,因為無法在 dataframe 中輸入該值,因此出現以下錯誤: 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)

在這里,您是 go。

如果您的任務太小,這有點矯枉過正,您需要將 RabbitMQ 設置為消息代理。 有關詳細信息,請參閱Celery 文檔

   (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>))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM