4

I have a question on handling ConnectionResetError in Python3. This usually happens when I use the urllib.request.Request function. I would like to know if it is ok to redo the request if we come across such error. For example

def get_html(url):
    try:
        request = Request(url)
        response = urlopen(request)
        html = response.read()
    except ConectionReserError as e:
        get_html(url)
Faiz Maricar
  • 51
  • 1
  • 1
  • 6

1 Answers1

7

It really depends on the server, but you could do something like:

def get_html(url, retry_count=0):
    try:
        request = Request(url)
        response = urlopen(request)
        html = response.read()
    except ConectionResetError as e:
        if retry_count == MAX_RETRIES:
            raise e
        time.sleep(for_some_time)
        get_html(url, retry_count + 1)

Also see Python handling socket.error: [Errno 104] Connection reset by peer

Community
  • 1
  • 1
yati sagade
  • 1,355
  • 9
  • 24