Alfred's spAcE

2016.02.10

decorator in python

Filed under: misc — Tags: — Alfred Yang @ 20:55

I write a script to check-in a web service; it consists of 1~3 http gets, and maybe one http post to login my account. It is very handy, I can use crontab to let it run by schedule, so if my computer is running, I won’t forget to check-in.

I often see the requests lib complains SSLError – “Unexpected EOF”; I’m not sure what’s the problem, but usually a retry can solve this problem. So I think of add a retry mechanism to all these gets and posts. The retry codes will be like this:

_retry_cnt = 3
while _retry_cnt > 0:
    try:
        # gets/posts
        break
    except:
        _retry_cnt -= 1
else:
    # too many error, quit
    quit()

But as you can see, I have to copy them to replace all gets/posts, it does not look like an good idea. After look up in python language reference, find decorator; so I don’t need to change all gets/posts, I just need to add a decorator before my gets/posts functions. I will be like this:

# decorator function to do 3 times retries
def web_try(Func):
    def action(*args, **kwds):
        _retry_cnt = 3 
        while _retry_cnt > 0:
            try:
                Func(*args, **kwds)
                break
            except:
                myprint('exception count down')
               _retry_cnt -= 1
        else:
            myprint('too many retries, abort mission!')
            quit()
    return action

# two functions need decorator
@web_try
def web_get(url):
    b.open(url) # b is a robobrowser object

@web_try
def web_auth(url, payload):
    b.session.post(url, data=payload)

So I don’t need to need to do code changes in main logic.