How to handle "HTTP error 502" in python?

903 views Asked by At

I,m trying to handle "HTTP ERROR 502" which is coming from reddit api service since its exceeding its Limit

So I'm trying to reconnect it by following code snippet:

import urllib
import urllib.request
from urllib.error import URLError, HTTPError
from urllib.request import Request, urlopen

try:
    with urllib3.request.urlopen(submission.url) as url:
        arr = np.asarray(bytearray(url.read()), dtype=np.uint8)
        rgb_img = cv2.imdecode(arr, -1) 
        cv2.imwrite(os.path.join('image_data',str(unique_name)+".jpg"),rgb_img)

except HTTPError as e:
    if e.code == 502:

        @retry(urllib.URLError, tries=4, delay=3, backoff=2)
         def urlopen_with_retry():
             return urllib.urlopen(submission.url)

          urlopen_with_retry()

    else:                    
        print ('Failure: ' + str(e.reason))

But this is not working and its giving error that "retry" is not a found in urlib

How to properly handle this HTTP 500 ish errors ?

0

There are 0 answers