发生异常后由谁/如何控制程序 - python

我一直想知道在引发异常后,谁来控制程序。我正在寻找一个明确的答案,但没有找到任何答案。我描述了以下函数,每个函数执行一个涉及网络请求的API调用,因此我需要通过try / except和else块(JSON响应也必须被解析/解码)处理任何可能的错误:

# This function runs first, if this fails, none of the other functions will run. Should return a JSON.
def get_summary():
    pass

# Gets executed after get_summary. Should return a string.
def get_block_hash():
    pass

# Gets executed after get_block_hash. Should return a JSON.
def get_block():
    pass

# Gets executed after get_block. Should return a JSON.
def get_raw_transaction():
    pass

我希望在每个函数上实现一种重试功能,因此,如果由于超时错误,连接错误,JSON解码错误等导致失败,它将继续重试而不会影响程序的流程:

def get_summary():
    try:
        response = request.get(API_URL_SUMMARY)
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        # Once response has been received, JSON should be 
        # decoded here wrapped in a try/catch/else
        # or outside of this block?
        return response.text

def get_block_hash():
    try:
        response = request.get(API_URL + "...")
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        return response.text

def get_block():
    try:
        response = request.get(API_URL + "...")
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        #
        #
        #
        return response.text

def get_raw_transaction():
    try:
        response = request.get(API_URL + "...")
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        #
        #
        #
        return response.text

if __name__ == "__main__":
    # summary = get_summary()
    # block_hash = get_block_hash()
    # block = get_block()
    # raw_transaction = get_raw_transaction()
    # ...

我想在其最外面的部分(if __name__ == "__main__":之后的块)中保留干净的代码,我的意思是,我不想用混乱的try / catch块,日志记录等填充它。

当这些函数中的任何一个发生异常时,我尝试调用一个函数本身,但随后我了解了堆栈限制,并认为这是一个坏主意,应该有一种更好的方法来处理此问题。

request当我调用get方法时,本身已经重试了N次,其中N是源代码中的常量,它是100。但是当重试次数达到0时,它将引发错误,我需要抓住。

我应该在哪里解码JSON响应?在每个函数内部并由另一个try / catch / else块包装吗?还是在主街区?如何从异常中恢复并继续尝试失败的功能?

任何建议将不胜感激。

参考方案

您可以将它们保持在无限循环中(以避免递归),一旦获得预期的响应,就返回:

def get_summary():
    while True:
        try:
            response = request.get(API_URL_SUMMARY)
        except requests.exceptions.RequestException as error:
            logging.warning("...")
            #
        else:
            # As winklerrr points out, try to return the transformed data as soon 
            # as possible, so you should be decoding JSON response here.
            try:
                json_response = json.loads(response)
            except ValueError as error: # ValueError will catch any error when decoding response
                logging.warning(error)
            else:
                return json_response

该函数将继续执行,直到收到预期结果(达到return json_response),否则它将一次又一次地尝试。

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

.get()之后,多处理陷入困境 - python

我试图了解multiprocessing如何在python中工作并遇到一些问题。这是示例:import multiprocessing def func(): return 1 p = multiprocessing.Pool() result = p.apply_async(func).get() 调用.get()函数时,代码只是卡住了。我究竟做错了什么?…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python:图像处理可产生皱纹纸效果 - python

也许很难描述我的问题。我正在寻找Python中的算法,以在带有某些文本的白色图像上创建皱纹纸效果。我的第一个尝试是在带有文字的图像上添加一些真实的皱纹纸图像(具有透明度)。看起来不错,但副作用是文本没有真正起皱。所以我正在寻找更好的解决方案,有什么想法吗?谢谢 参考方案 除了使用透明性之外,假设您有两张相同尺寸的图像,一张在皱纹纸上明亮,一张在白色背景上有深…