Python Glossary Русский

all Python 3urllib.requestterm

urllib.request.HTTPDefaultErrorHandler

errors and redirects

The last link in HTTP error handling: it turns everything the others did not handle into urllib.error.HTTPError.

Syntax

urllib.request.HTTPDefaultErrorHandler()

Because of it urlopen() does not return a 404 or 500 response but raises. The error body is not lost: e.read() and e.code work, since HTTPError is itself a response. To get such responses like normal ones, replace it with a subclass whose http_error_default returns fp.

Examples

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, 404, b'not here')
try:
    urllib.request.build_opener(Server).open('http://example.com/x')
except urllib.error.HTTPError as e:
    print(e.code, e.read())  # → 404 b'not here'
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, 500, b'oops')
class Keep(urllib.request.HTTPDefaultErrorHandler):
    def http_error_default(self, req, fp, code, msg, hdrs):
        return fp
resp = urllib.request.build_opener(Server, Keep).open('http://example.com/x')
print(resp.status, resp.read())  # → 500 b'oops'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy