codekingpro/portable-devtools
114k
1import requests2 3from ._compat import urljoin4 5 6class BaseUrlSession(requests.Session):7 """A Session with a URL that all requests will use as a base.8 9 Let's start by looking at a few examples:10 11 .. code-block:: python12 13 >>> from requests_toolbelt import sessions14 >>> s = sessions.BaseUrlSession(15 ... base_url='https://example.com/resource/')16 >>> r = s.get('sub-resource/', params={'foo': 'bar'})17 >>> print(r.request.url)18 https://example.com/resource/sub-resource/?foo=bar19 20 Our call to the ``get`` method will make a request to the URL passed in21 when we created the Session and the partial resource name we provide.22 We implement this by overriding the ``request`` method of the Session.23 24 Likewise, we override the ``prepare_request`` method so you can construct25 a PreparedRequest in the same way:26 27 .. code-block:: python28 29 >>> from requests import Request30 >>> from requests_toolbelt import sessions31 >>> s = sessions.BaseUrlSession(32 ... base_url='https://example.com/resource/')33 >>> request = Request(method='GET', url='sub-resource/')34 >>> prepared_request = s.prepare_request(request)35 >>> r = s.send(prepared_request)36 >>> print(r.request.url)37 https://example.com/resource/sub-resource38 39 .. note::40 41 The base URL that you provide and the path you provide are **very**42 important.43 44 Let's look at another *similar* example45 46 .. code-block:: python47 48 >>> from requests_toolbelt import sessions49 >>> s = sessions.BaseUrlSession(50 ... base_url='https://example.com/resource/')51 >>> r = s.get('/sub-resource/', params={'foo': 'bar'})52 >>> print(r.request.url)53 https://example.com/sub-resource/?foo=bar54 55 The key difference here is that we called ``get`` with ``/sub-resource/``,56 i.e., there was a leading ``/``. This changes how we create the URL57 because we rely on :mod:`urllib.parse.urljoin`.58 59 To override how we generate the URL, sub-class this method and override the60 ``create_url`` method.61 62 Based on implementation from63 https://github.com/kennethreitz/requests/issues/2554#issuecomment-10934101064 """65 66 base_url = None67 68 def __init__(self, base_url=None):69 if base_url:70 self.base_url = base_url71 super(BaseUrlSession, self).__init__()72 73 def request(self, method, url, *args, **kwargs):74 """Send the request after generating the complete URL."""75 url = self.create_url(url)76 return super(BaseUrlSession, self).request(77 method, url, *args, **kwargs78 )79 80 def prepare_request(self, request, *args, **kwargs):81 """Prepare the request after generating the complete URL."""82 request.url = self.create_url(request.url)83 return super(BaseUrlSession, self).prepare_request(84 request, *args, **kwargs85 )86 87 def create_url(self, url):88 """Create the URL based off this partial path."""89 return urljoin(self.base_url, url)90 