Advertisement
cmiN

gae-requests-patch

May 19th, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. """Runtime monkey-patching for various problematic libraries."""
  2.  
  3.  
  4. import re
  5.  
  6. import requests
  7. from requests.cookies import MockRequest
  8.  
  9.  
  10. class MockResponse(object):
  11.     """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
  12.  
  13.    ...what? Basically, expose the parsed HTTP headers from the server response
  14.    the way `cookielib` expects to see them.
  15.    """
  16.  
  17.     SEPARATOR = re.compile(r",\s*(?=[\w-]+=)")
  18.  
  19.     def __init__(self, response):
  20.         """Make a MockResponse for `cookielib` to read.
  21.  
  22.        :param response: a HTTPResponse or analogous carrying the headers
  23.        """
  24.         self._response = response
  25.  
  26.     def info(self):
  27.         return self
  28.  
  29.     def getheaders(self, name):
  30.         headers = self._response.getheader(name)
  31.         return self.SEPARATOR.split(headers) if headers else []
  32.  
  33.  
  34. def extract_cookies_to_jar(jar, request, response):
  35.     """Extract the cookies from the response into a CookieJar.
  36.  
  37.    :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
  38.    :param request: our own requests.Request object
  39.    :param response: urllib3.HTTPResponse object
  40.    """
  41.     # the _original_response field is the wrapped httplib.HTTPResponse object,
  42.     req = MockRequest(request)
  43.     # pull out the HTTPMessage with the headers and put it in the mock:
  44.     res = MockResponse(response)
  45.     jar.extract_cookies(res, req)
  46.  
  47.  
  48. def _monkeypatch_requests():
  49.     """Monkey patch that problematic cookie extraction function."""
  50.     modules = [
  51.         # Patch the entire namespace within Python.
  52.         requests.adapters,
  53.         requests.auth,
  54.         requests.cookies,
  55.         requests.sessions,
  56.     ]
  57.     for module in modules:
  58.         setattr(module, "extract_cookies_to_jar", extract_cookies_to_jar)
  59.  
  60.  
  61. def monkeypatch():
  62.     _monkeypatch_requests()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement