[英]Dynamic parameters with Python's retry decorator
我目前正在使用python 重試包,其中包含具有許多可選參數的@retry
裝飾器。 我為我們的生產環境正確設置了這些參數,重試之間的等待時間足夠長(低於 2000 毫秒),但我想為單元測試目的設置不同的這些值,以便執行速度非常快。
例如,這里的 wait_fixed 時間設置為 2000 毫秒以用於生產,但對於調用some_function()
單元測試,我想將wait_fixed
參數覆蓋為 1 毫秒,以便它執行得非常快。
@retry(stop_max_attempt_number=3, wait_fixed=2000)
def some_function(self):
return True
main.py
import settings
from retrying import retry
@retry(stop_max_attempt_number=settings.STOP_MAX_ATTEMPT_NUMBER,
wait_fixed=settings.WAIT_FIXED)
def some_function(self):
return True
settings.py
import json
with open('config.json') as jsonf:
config = json.loads(jsonf.read())
WAIT_FIXED=int(config['WAIT_FIXED'])
STOP_MAX_ATTEMPT_NUMBER=int(config['STOP_MAX_ATTEMPT_NUMBER'])
config.json
{
"STOP_MAX_ATTEMPT_NUMBER" : "3",
"WAIT_FIXED" : "2000"
}
讓你的測試運行器放置一個合適的config.json
到位。
我最近遇到了一個問題,在def
有一個def
解決了這個問題。
我需要在get_url
函數上使用重試裝飾器,但需要為stop_max_attempt_number
傳遞可配置值。 我無法想出get_url
以及相同縮進的其他函數。
為了解決這個問題,我有get_url
里面定義的函數get_analytic
功能。 舉例說明:
def get_analytics(conf: Configuration, assets: list, cache: dict) -> list:
STOP_MAX_ATTEMPT_NUMBER = int(conf.num_retry)
WAIT_FIXED = int(conf.retry_timeout)
@retry(stop_max_attempt_number=STOP_MAX_ATTEMPT_NUMBER, wait_fixed=WAIT_FIXED)
def get_url(disable_https: bool, url: str, user: str, password: str) -> Response:
我需要能夠在調用函數時動態設置重試參數,以下對我來說效果很好:
import random
from retrying import retry
class MyClass(object):
def try_stuff(self, string, attempts, wait):
self.do_something_with_retry = retry(stop_max_attempt_number=attempts,
wait_fixed=wait)(self.do_something_unreliable)
return self.do_something_with_retry(string)
def do_something_unreliable(self, string):
print(string)
if random.randint(0, 10) > 1:
raise IOError("Broken sauce, everything is hosed!!!111one")
else:
return "Awesome sauce!"
instance = MyClass()
print instance.try_stuff('test', 10, 2000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.