all Python 3urllib.requestterm
urllib.request.HTTPErrorProcessor
errors and redirects
A post-processor for HTTP responses: everything outside the 2xx range goes to the error-handling chain.
Syntax
urllib.request.HTTPErrorProcessor()
It is what decides that a 3xx, 401 or 500 is an event rather than a response: redirects, authentication and finally HTTPDefaultErrorHandler with HTTPError take over. It sits last in the chain (handler_order 1000). For file: and data: it is never called — there are no HTTP codes, and resp.status is None.
Examples
import urllib.request
print(urllib.request.HTTPErrorProcessor.handler_order) # → 1000
with urllib.request.urlopen('data:,x') as resp:
print(resp.status) # → None
import email.message, io, urllib.error, urllib.request, urllib.response
def reply(req, code, body=b'', **headers):
msg = email.message.Message()
for name, value in headers.items():
msg[name.replace('_', '-')] = value
resp = urllib.response.addinfourl(io.BytesIO(body), msg, req.full_url, code)
resp.msg = 'demo'
return resp
class Server(urllib.request.BaseHandler):
handler_order = 100
def http_open(self, req):
return reply(req, 503, b'busy')
try:
urllib.request.build_opener(Server).open('http://example.com/')
except urllib.error.HTTPError as e:
print('HTTPError', e.code) # → HTTPError 503
See also
Open in the full glossarydocs.python.orgReport an inaccuracy