Home Backend Development Python Tutorial python重试装饰器示例

python重试装饰器示例

Jun 06, 2016 am 11:29 AM
Decorator

利用python 写一些网络服务的时候,当网络状况不好,或者资源占用过多,任务拥塞的情况下,总会抛出一些异常,当前任务就被终止了,可以很好的利用@装饰器,写一个重试的装饰器,这样比较python!
执行结果:

代码如下:


WARNING:root:timed out, Retrying in 3 seconds...
WARNING:root:timed out, Retrying in 6 seconds...
WARNING:root:timed out, Retrying in 12 seconds...

代码如下:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  tanyewei@gmail.com
#  2014/01/27 10:36
import time
import logging
import socket
from functools import wraps

logging.basicConfig(level=logging.DEBUG)

def retry(MyException, tries=4, delay=3, backoff=2, logger=None):
    def deco_retry(f):
        @wraps(f)
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except MyException as ex:
                    msg = "%s, Retrying in %d seconds..." % (str(ex), mdelay)
                    if logger:
                        logger.warning(msg)
                    else:
                        print msg
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return str(ex)

        return f_retry

    return deco_retry

@retry(Exception, logger=logging)
def check():
    sk = socket.socket()
    sk.settimeout(5)
    sk.connect(('6.6.6.6', 80))

if __name__ == "__main__":
    check()

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Teach you step by step how to use decorators to extend Python timers Teach you step by step how to use decorators to extend Python timers Apr 13, 2023 pm 08:46 PM

This is our third article to teach you step by step how to implement a Python timer. The first two articles: teach you step by step how to implement a Python timer, and use context managers to extend Python timers, making our Timer class convenient to use, beautiful and practical. But we are not satisfied with this, there is still a use case that can simplify it further. Suppose we need to track the time spent in a given function in our code base. With a context manager, you basically have two different options: 1. Use ​Timer every time you call a function: with Timer("some_name"): do_something() When we are in

How do decorators and context managers work in Python? How do decorators and context managers work in Python? Oct 20, 2023 pm 07:04 PM

How do decorators and context managers work in Python? In Python, decorators and context managers are two very useful concepts and features. They are all designed to simplify code, increase code readability, and facilitate code reuse. 1. Decorator A decorator is a special function in Python that is used to modify the behavior of a function. It allows us to wrap or extend the original function without modifying it. Decorators are widely used in many Python frameworks and libraries, such as Flask, Dj

Debugging Pytorch memory leak issues using context decorators Debugging Pytorch memory leak issues using context decorators Apr 10, 2023 am 11:31 AM

Decorators are specific implementations of python context managers. This article will illustrate how to use them through an example of pytorch GPU debugging. While it may not work in every situation, I found them to be very useful. Debugging Memory Leak Issues There are many ways to debug memory leaks. This article will demonstrate a useful method for identifying problematic lines in your code. This method can help to find the specific location in a concise way. Manual debugging line by line If you encounter a problem, a classic and commonly used method is to use the debugger to check line by line, such as the following example: Find code snippets on how to calculate the total number of all tensors in pytorch in the search engine, such as: tensor -counter-s

Understand Python decorators in one article Understand Python decorators in one article Apr 12, 2023 pm 09:40 PM

Python is a beginner-friendly language. However, it also has many advanced features that are difficult to master, such as decorators. Many beginners have never understood decorators and how they work. In this article, we will introduce the ins and outs of decorators. In Python, a function is a very flexible structure that can be assigned to a variable, passed as a parameter to another function, or used as the output of a function. A decorator is essentially a function that allows other functions to add some functionality without modification. This is the meaning of "decoration". This "decoration" itself represents a function. If you use it to modify different functions, it will add this function to these functions.

Python programming: Re-understanding of decorator functions Python programming: Re-understanding of decorator functions May 27, 2023 pm 03:57 PM

Decorators are very useful tools in Python. A decorator is a function that takes another function as a parameter and extends its functionality without explicitly modifying it. It allows us to modify the behavior of a function or class without touching its source code. In other words, a decorator wraps a function to extend its behavior rather than permanently modifying it. Starting from this article, let’s study what decorators are and how they work in Python. 1.1 About functions In order to understand how decorators work, we need to review some important concepts about functions in Python. Always be aware that in Python, functions (functions) are first-class citizens, so the following concepts should be kept in mind: ü functions

Common problems and solutions for decorators in Python Common problems and solutions for decorators in Python Oct 10, 2023 am 11:58 AM

Frequently Asked Questions and Solutions about Decorators in Python What are decorators? Decorators are a very powerful feature in Python that can be used to modify the behavior of existing functions or classes without modifying their source code. A decorator is actually a function or class that accepts a function or class as a parameter and returns a new function or class. How to write a simple decorator? Here is an example of a simple decorator: defdecorator(func):definner_func

Python programming: How to implement class decorators and applications? Key points to grasp Python programming: How to implement class decorators and applications? Key points to grasp Apr 12, 2023 pm 05:25 PM

Example Decorators in Python can be either functions or classes. In the previous sections, we used function decorators. Now, we will learn how to define class decorators. We will define a custom class that acts as a decorator. When a function is decorated/modified with a class, the function becomes an instance of that class. Let’s find out: As shown above, we created a simple class decorator. For any class to become a decorator, it needs to implement the __call__() method. The __call__() method works the same as a wrapper function in a function decorator. Now let us use this class to decorate a function: The output of running the program is as follows: Class decorator with *args and **kwargs parameters. In order to let the class decorator use parameters, use

Understanding and applying Python decorators Understanding and applying Python decorators May 08, 2023 am 08:10 AM

Decorator is an advanced Python syntax. A function, method or class can be processed. In Python, we have multiple methods to process functions and classes. Compared with other methods, decorators have simple syntax and high code readability. Therefore, decorators are widely used in Python projects. Decorators are often used in scenarios with cross-cutting requirements. Classic examples include insertion logs, performance testing, transaction processing, Web permission verification, Cache, etc. The advantage of decorators is that they can extract the same code in a large number of functions that has nothing to do with the function itself and continue to reuse it. That is, functions can be "modified" into completely different behaviors, and business logic can be effectively decomposed orthogonally. Generally speaking, decoration

See all articles