| 392 | return list(hdrs.items()) |
| 393 | |
| 394 | class OpenerDirector: |
| 395 | def __init__(self): |
| 396 | client_version = "Python-urllib/%s" % __version__ |
| 397 | self.addheaders = [('User-agent', client_version)] |
| 398 | # self.handlers is retained only for backward compatibility |
| 399 | self.handlers = [] |
| 400 | # manage the individual handlers |
| 401 | self.handle_open = {} |
| 402 | self.handle_error = {} |
| 403 | self.process_response = {} |
| 404 | self.process_request = {} |
| 405 | |
| 406 | def add_handler(self, handler): |
| 407 | if not hasattr(handler, "add_parent"): |
| 408 | raise TypeError("expected BaseHandler instance, got %r" % |
| 409 | type(handler)) |
| 410 | |
| 411 | added = False |
| 412 | for meth in dir(handler): |
| 413 | if meth in ["redirect_request", "do_open", "proxy_open"]: |
| 414 | # oops, coincidental match |
| 415 | continue |
| 416 | |
| 417 | i = meth.find("_") |
| 418 | protocol = meth[:i] |
| 419 | condition = meth[i+1:] |
| 420 | |
| 421 | if condition.startswith("error"): |
| 422 | j = condition.find("_") + i + 1 |
| 423 | kind = meth[j+1:] |
| 424 | try: |
| 425 | kind = int(kind) |
| 426 | except ValueError: |
| 427 | pass |
| 428 | lookup = self.handle_error.get(protocol, {}) |
| 429 | self.handle_error[protocol] = lookup |
| 430 | elif condition == "open": |
| 431 | kind = protocol |
| 432 | lookup = self.handle_open |
| 433 | elif condition == "response": |
| 434 | kind = protocol |
| 435 | lookup = self.process_response |
| 436 | elif condition == "request": |
| 437 | kind = protocol |
| 438 | lookup = self.process_request |
| 439 | else: |
| 440 | continue |
| 441 | |
| 442 | handlers = lookup.setdefault(kind, []) |
| 443 | if handlers: |
| 444 | bisect.insort(handlers, handler) |
| 445 | else: |
| 446 | handlers.append(handler) |
| 447 | added = True |
| 448 | |
| 449 | if added: |
| 450 | bisect.insort(self.handlers, handler) |
| 451 | handler.add_parent(self) |
no outgoing calls