all Python 3urllib.requestterm
urllib.request.BaseHandler
openers
The base class of urllib handlers: inherit from it to add your own schemes or to adjust requests and responses.
Syntax
class MyHandler(urllib.request.BaseHandler): def <scheme>_open(self, req): ...
Methods are found by name: <scheme>_open(req) opens a URL, <scheme>_request(req) adjusts the request before sending, <scheme>_response(req, resp) the response afterwards, and http_error_<code> handles an error. A typo in a method name raises nothing — the handler is simply never called. The handler_order attribute sets the position in the chain: lower runs earlier, 500 by default.
Examples
import io, urllib.request, urllib.response
class Echo(urllib.request.BaseHandler):
def echo_open(self, req):
body = req.selector.encode()
return urllib.response.addinfourl(io.BytesIO(body), {}, req.full_url)
opener = urllib.request.build_opener(Echo)
print(opener.open('echo://demo/hello').read()) # → b'/hello'
print(Echo.handler_order) # → 500
See also
Open in the full glossarydocs.python.orgReport an inaccuracy