sessions.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import requests
  2. from ._compat import urljoin
  3. class BaseUrlSession(requests.Session):
  4. """A Session with a URL that all requests will use as a base.
  5. Let's start by looking at an example:
  6. .. code-block:: python
  7. >>> from requests_toolbelt import sessions
  8. >>> s = sessions.BaseUrlSession(
  9. ... base_url='https://example.com/resource/')
  10. >>> r = s.get('sub-resource/' params={'foo': 'bar'})
  11. >>> print(r.request.url)
  12. https://example.com/resource/sub-resource/?foo=bar
  13. Our call to the ``get`` method will make a request to the URL passed in
  14. when we created the Session and the partial resource name we provide.
  15. We implement this by overriding the ``request`` method so most uses of a
  16. Session are covered. (This, however, precludes the use of PreparedRequest
  17. objects).
  18. .. note::
  19. The base URL that you provide and the path you provide are **very**
  20. important.
  21. Let's look at another *similar* example
  22. .. code-block:: python
  23. >>> from requests_toolbelt import sessions
  24. >>> s = sessions.BaseUrlSession(
  25. ... base_url='https://example.com/resource/')
  26. >>> r = s.get('/sub-resource/' params={'foo': 'bar'})
  27. >>> print(r.request.url)
  28. https://example.com/sub-resource/?foo=bar
  29. The key difference here is that we called ``get`` with ``/sub-resource/``,
  30. i.e., there was a leading ``/``. This changes how we create the URL
  31. because we rely on :mod:`urllib.parse.urljoin`.
  32. To override how we generate the URL, sub-class this method and override the
  33. ``create_url`` method.
  34. Based on implementation from
  35. https://github.com/kennethreitz/requests/issues/2554#issuecomment-109341010
  36. """
  37. base_url = None
  38. def __init__(self, base_url=None):
  39. if base_url:
  40. self.base_url = base_url
  41. super(BaseUrlSession, self).__init__()
  42. def request(self, method, url, *args, **kwargs):
  43. """Send the request after generating the complete URL."""
  44. url = self.create_url(url)
  45. return super(BaseUrlSession, self).request(
  46. method, url, *args, **kwargs
  47. )
  48. def create_url(self, url):
  49. """Create the URL based off this partial path."""
  50. return urljoin(self.base_url, url)