0

我正在编写一些 Python 代码来处理对 Web 服务的调用。

def calculate(self):
    market_supply_price = self.__price_to_pay_current_market_supply()
    market_supply_price_usd = market_supply_price.get('usd')
    market_supply_price_eur = market_supply_price.get('eur')
    amount = '%.8f' % ((self.euro - ((self.euro*self.__tax_to_apply())+self.__extra_tax_to_apply())) / market_supply_price_eur)
    return {'usd': [market_supply_price_usd, amount], 'eur': [market_supply_price_eur, amount]}

对 web 服务的调用在这一行:

market_supply_price = self.__price_to_pay_current_market_supply()

这个私有方法对 web 服务进行各种调用并返回结果。我的问题是这个网络服务失败了很多。我需要实现一种方法,如果其中一个调用失败,我将等待例如 10 分钟并重试,如果 10 分钟后再次失败,我将等待 30 分钟并重试,如果 30 分钟后再次失败,我将等待 60 分钟...

在 calculate() 方法中实现这样的最佳方法是什么?

我已经实现了这样的东西,但它看起来是错误的,而不是应该做的方式。

def calculate(self):
    try:
        market_supply_price = self.__price_to_pay_current_market_supply()
    except:
        pass
        try:
            time.sleep(600)
            market_supply_price = self.__price_to_pay_current_market_supply()
        except:
            pass
            try:
                time.sleep(600)
                market_supply_price = self.__price_to_pay_current_market_supply()
            except:
                pass
                try:
                    time.sleep(1200)
                    market_supply_price = self.__price_to_pay_current_market_supply()
                except:
                    sys.exit(1)
    market_supply_price_usd = market_supply_price.get('usd')
    market_supply_price_eur = market_supply_price.get('eur')
    amount = '%.8f' % ((self.euro - ((self.euro*self.__tax_to_apply())+self.__extra_tax_to_apply())) / market_supply_price_eur)
    return {'usd': [market_supply_price_usd, amount], 'eur': [market_supply_price_eur, amount]}

关于如何以正确的方式做到这一点的任何线索?

此致,

4

1 回答 1

0

循环适用于这种类型的事情。这是您指定超时的示例:

def calculate(self):
    for timeout in (600, 600, 1200):
        try:
            market_supply_price = self.__price_to_pay_current_market_supply()
            break
        except: # BAD! Catch specific exceptions
            sleep(timeout)
    else:
        print "operation failed"
        sys.exit(1)

    market_supply_price_usd = market_supply_price.get('usd')
    market_supply_price_eur = market_supply_price.get('eur')
    etc...
于 2014-01-30T20:31:51.463 回答