comparison planemo/lib/python3.7/site-packages/requests_toolbelt/sessions.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
1 import requests
2
3 from ._compat import urljoin
4
5
6 class 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 an example:
10
11 .. code-block:: python
12
13 >>> from requests_toolbelt import sessions
14 >>> 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=bar
19
20 Our call to the ``get`` method will make a request to the URL passed in
21 when we created the Session and the partial resource name we provide.
22
23 We implement this by overriding the ``request`` method so most uses of a
24 Session are covered. (This, however, precludes the use of PreparedRequest
25 objects).
26
27 .. note::
28
29 The base URL that you provide and the path you provide are **very**
30 important.
31
32 Let's look at another *similar* example
33
34 .. code-block:: python
35
36 >>> from requests_toolbelt import sessions
37 >>> s = sessions.BaseUrlSession(
38 ... base_url='https://example.com/resource/')
39 >>> r = s.get('/sub-resource/' params={'foo': 'bar'})
40 >>> print(r.request.url)
41 https://example.com/sub-resource/?foo=bar
42
43 The key difference here is that we called ``get`` with ``/sub-resource/``,
44 i.e., there was a leading ``/``. This changes how we create the URL
45 because we rely on :mod:`urllib.parse.urljoin`.
46
47 To override how we generate the URL, sub-class this method and override the
48 ``create_url`` method.
49
50 Based on implementation from
51 https://github.com/kennethreitz/requests/issues/2554#issuecomment-109341010
52 """
53
54 base_url = None
55
56 def __init__(self, base_url=None):
57 if base_url:
58 self.base_url = base_url
59 super(BaseUrlSession, self).__init__()
60
61 def request(self, method, url, *args, **kwargs):
62 """Send the request after generating the complete URL."""
63 url = self.create_url(url)
64 return super(BaseUrlSession, self).request(
65 method, url, *args, **kwargs
66 )
67
68 def create_url(self, url):
69 """Create the URL based off this partial path."""
70 return urljoin(self.base_url, url)