1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
>>> import io
>>> from mechanize import _opener, HTTPError
Normal case. Response goes through hook function and is returned.
>>> def urlopen(fullurl, data=None, timeout=None):
... print("fullurl %r" % fullurl)
... print("data %r" % data)
... return "response"
>>> def response_hook(response):
... print("response %r" % response)
... return "processed response"
>>> _opener.wrapped_open(urlopen, response_hook,
... "http://example.com", "data"
... )
fullurl 'http://example.com'
data 'data'
response 'response'
'processed response'
Raised HTTPError exceptions still go through the response hook but
the result is raised rather than returned.
>>> def urlopen(fullurl, data=None, timeout=None):
... print("fullurl %r" % fullurl)
... print("data %r" % data)
... raise HTTPError(
... "http://example.com", 200, "OK", {}, io.BytesIO())
>>> def response_hook(response):
... print("response class %s" % response.__class__.__name__)
... return Exception("processed response")
>>> try:
... _opener.wrapped_open(urlopen, response_hook,
... "http://example.com", "data"
... )
... except Exception as exc:
... print(exc)
fullurl 'http://example.com'
data 'data'
response class HTTPError
processed response
Other exceptions get ignored, since they're not response objects.
>>> def urlopen(fullurl, data=None, timeout=None):
... print("fullurl %r" % fullurl)
... print("data %r" % data)
... raise Exception("not caught")
>>> try:
... _opener.wrapped_open(urlopen, response_hook,
... "http://example.com", "data"
... )
... except Exception as exc:
... print(exc)
fullurl 'http://example.com'
data 'data'
not caught
|