Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #43161

Re: newbie question about confusing exception handling in urllib

Path csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!rt.uk.eu.org!newsfeed.xs4all.nl!newsfeed1.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <python-python-list@m.gmane.org>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'example:': 0.03; 'else:': 0.03; 'none:': 0.07; 'python3': 0.07; 'skip:u 30': 0.07; 'ugly': 0.07; 'below).': 0.09; 'except:': 0.09; 'here?': 0.09; 'msg': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'try:': 0.09; 'subject:question': 0.10; 'python': 0.11; 'def': 0.12; 'project,': 0.12; 'errno': 0.16; 'exceptions,': 0.16; 'fetch': 0.16; 'mean,': 0.16; 'nightmare': 0.16; 'received:80.91.229.3': 0.16; 'received:dip.t-dialin.net': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-dialin.net': 0.16; 'recently.': 0.16; 'request)': 0.16; 'subject:exception': 0.16; 'subject:handling': 0.16; 'urllib': 0.16; 'exception': 0.16; 'wrote:': 0.18; 'trying': 0.19; 'reset': 0.22; 'header:User-Agent:1': 0.23; 'error': 0.23; 'fine': 0.24; 'looks': 0.24; 'handling': 0.26; 'skip:" 30': 0.26; 'pass': 0.26; 'header:X-Complaints-To:1': 0.27; 'tried': 0.27; 'raise': 0.29; 'field,': 0.30; 'statement': 0.30; 'skip:( 20': 0.30; 'program,': 0.31; 'code': 0.31; 'catching': 0.31; 'directly,': 0.31; 'exceptions': 0.31; 'class': 0.32; 'there.': 0.32; 'checking': 0.33; 'totally': 0.33; 'could': 0.34; 'common': 0.35; 'connection': 0.35; 'except': 0.35; 'something': 0.35; 'requirement': 0.35; 'but': 0.35; 'there': 0.35; 'really': 0.36; 'returning': 0.36; 'doing': 0.36; 'possible': 0.36; 'hi,': 0.36; 'should': 0.36; 'so,': 0.37; 'too': 0.37; 'level': 0.37; 'sometimes': 0.38; 'to:addr:python-list': 0.38; 'does': 0.39; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'how': 0.40; 'skip:u 10': 0.60; 'catch': 0.60; 'simple,': 0.60; 'break': 0.61; 'simple': 0.61; 'first': 0.61; 'times': 0.62; 'email addr:gmail.com': 0.63; 'field': 0.63; 'became': 0.64; 'become': 0.64; 'different': 0.65; 'details': 0.65; 'fails,': 0.84
X-Injected-Via-Gmane http://gmane.org/
To python-list@python.org
From Peter Otten <__peter__@web.de>
Subject Re: newbie question about confusing exception handling in urllib
Date Tue, 09 Apr 2013 14:19:06 +0200
Organization None
References <1ae3261b-078d-4362-abff-ea4471addd6a@googlegroups.com>
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Gmane-NNTP-Posting-Host p5084b0de.dip.t-dialin.net
User-Agent KNode/4.7.3
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.344.1365509864.3114.python-list@python.org> (permalink)
Lines 90
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1365509864 news.xs4all.nl 6948 [2001:888:2000:d::a6]:45864
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:43161

Show key headers only | View raw


cabbar@gmail.com wrote:

> Hi,
> 
> I have been using Java/Perl professionally for many years and have been
> trying to learn python3 recently. As my first program, I tried writing a
> class for a small project, and I am having really hard time understanding
> exception handling in urllib and in python in general... Basically, what I
> want to do is very simple, try to fetch something
> "tryurllib.request.urlopen(request)", and:
>   - If request times out or connection is reset, re-try n times
>   - If it fails, return an error
>   - If it works return the content.
> 
> But, this simple requirement became a nightmare for me. I am really
> confused about how I should be checking this because:
>   - When connection times out, I sometimes get URLException with "reason"
>   field set to socket.timeout, and checking (isinstance(exception.reason,
>   socket.timeout)) works fine - But sometimes I get socket.timeout
>   exception directly, and it has no "reason" field, so above statement
>   fails, since there is no reason field there. - Connection reset is a
>   totally different exception - Not to mention, some exceptions have msg /
>   reason / errno fields but some don't, so there is no way of knowing
>   exception details unless you check them one by one. The only common
>   thing I could was to find call __str__()? - Since, there are too many
>   possible exceptions, you need to catch BaseException (I received
>   URLError, socket.timeout, ConnectionRefusedError, ConnectionResetError,
>   BadStatusLine, and none share a common parent). And, catching the top
>   level exception is not a good thing.
> 
> So, I ended up writing the following, but from everything I know, this
> looks really ugly and wrong???
> 
>         try:
>             response = urllib.request.urlopen(request)
>             content = response.read()
>         except BaseException as ue:
>             if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason")
>             and isinstance(ue.reason, socket.timeout)) or isinstance(ue,
>             ConnectionResetError)):
>                 print("REQUEST TIMED OUT")
> 
> or, something like:
> 
>         except:
>             (a1,a2,a3) = sys.exc_info()
>             errorString = a2.__str__()
>             if ((errorString.find("Connection reset by peer") >= 0) or
>             (errorString.find("error timed out") >= 0)):
> 
> Am I missing something here? I mean, is this really how I should be doing
> it?

Does it help if you reorganize your code a bit? For example:

def read_content(request)
    try:
        response = urllib.request.urlopen(request)
        content = response.read()
    except socket.timeout:
        return None
    except URLError as ue:
        if isinstance(ue.reason, socket.timeout):
            return None
        raise
    return content

for i in range(max_tries):
    content = read_content(request)
    if content is not None:
        break
else:
    print("Could not download", request)

Instead of returning an out-of-band response (None) you could also raise a 
custom exception (called MyTimeoutError below). The retry-loop would then 
become

for i in range(max_tries):
    try:
        content = read_content(request):
    except MyTimeoutError:
        pass
    else:
        break
else:
    print("Could not download", request)


Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

newbie question about confusing exception handling in urllib cabbar@gmail.com - 2013-04-09 04:41 -0700
  Re: newbie question about confusing exception handling in urllib Peter Otten <__peter__@web.de> - 2013-04-09 14:19 +0200
  Re: newbie question about confusing exception handling in urllib cabbar@gmail.com - 2013-04-09 06:19 -0700
    Re: newbie question about confusing exception handling in urllib Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-04-09 15:05 +0000
      Re: newbie question about confusing exception handling in urllib Chris Angelico <rosuav@gmail.com> - 2013-04-10 02:23 +1000
      RE: newbie question about confusing exception handling in urllib "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2013-04-12 21:29 +0000
  Re: newbie question about confusing exception handling in urllib Terry Jan Reedy <tjreedy@udel.edu> - 2013-04-09 10:19 -0400
  Re: newbie question about confusing exception handling in urllib Ian Kelly <ian.g.kelly@gmail.com> - 2013-04-09 13:11 -0600

csiph-web