[Python] 發送http get/post request (處理編碼+延時重試)

import urllib2
import urllib
import time
import logging

class HttpRequester(object):

    def __init__(self):
        self.__retryCount = 3
        self.__retrySeconds = 5
            
    def sendPostWithRetry(self, url, data, encoding):
        count = 0
        while(count<self.__retryCount):
            try:
                req = urllib2.Request(url, urllib.urlencode(data))
                f = urllib2.urlopen(req)
                if(f.getcode()==200):
                    return f.read().decode(encoding)
                else:
                    count = count + 1
                    print('Retry after {0} seconds...'.format(str(self.__retrySeconds)))
                    time.sleep(5)
                    if(count>=self.__retryCount):
                        logging.ERROR('Has retried {0} times!!'.format(self.__retryCount))
                        raise Exception('Has retried {0} times!!'.format(self.__retryCount))
            except Exception as e:
                logging.warn(str(e))
                return None
        return None
    
    def sendGetWithRetry(self, url, encoding):
        count = 0
        while(count<self.__retryCount):
            try:
                f = urllib2.urlopen(url)
                if(f.getcode()==200):
                    return f.read().decode(encoding)
                else:
                    count = count + 1
                    print('Retry after {0} seconds...'.format(str(self.__retrySeconds)))
                    time.sleep(5)
                    if(count>=self.__retryCount):
                        logging.ERROR('Has retried {0} times!!'.format(self.__retryCount))
                        raise Exception('Has retried {0} times!!'.format(self.__retryCount))
            except Exception as e:
                logging.error(str(e))
                return None
        return None

如需要將延時設成random,則

import random

def __init__(self):
       self.__retryCount = 3
       self.__retrySeconds = random.randint(1,60) #隨機1-60秒