繁体   English   中英

Python-无法访问时如何处理Web服务?

[英]Python - How to deal with webservice when not accessible?

我正在编写一些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]}

对该网络服务的调用位于以下行:

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]}

有关如何正确执行此操作的任何线索?

最好的祝福,

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

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...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM