d5aa62d887f90675093eca880cb224129aa99cf3
[sdc/sdc-distribution-client.git] /
1 from __future__ import absolute_import
2 try:
3     from urllib.parse import urlencode
4 except ImportError:
5     from urllib import urlencode
6
7 from .filepost import encode_multipart_formdata
8
9
10 __all__ = ['RequestMethods']
11
12
13 class RequestMethods(object):
14     """
15     Convenience mixin for classes who implement a :meth:`urlopen` method, such
16     as :class:`~urllib3.connectionpool.HTTPConnectionPool` and
17     :class:`~urllib3.poolmanager.PoolManager`.
18
19     Provides behavior for making common types of HTTP request methods and
20     decides which type of request field encoding to use.
21
22     Specifically,
23
24     :meth:`.request_encode_url` is for sending requests whose fields are
25     encoded in the URL (such as GET, HEAD, DELETE).
26
27     :meth:`.request_encode_body` is for sending requests whose fields are
28     encoded in the *body* of the request using multipart or www-form-urlencoded
29     (such as for POST, PUT, PATCH).
30
31     :meth:`.request` is for making any kind of request, it will look up the
32     appropriate encoding format and use one of the above two methods to make
33     the request.
34
35     Initializer parameters:
36
37     :param headers:
38         Headers to include with all requests, unless other headers are given
39         explicitly.
40     """
41
42     _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])
43
44     def __init__(self, headers=None):
45         self.headers = headers or {}
46
47     def urlopen(self, method, url, body=None, headers=None,
48                 encode_multipart=True, multipart_boundary=None,
49                 **kw):  # Abstract
50         raise NotImplemented("Classes extending RequestMethods must implement "
51                              "their own ``urlopen`` method.")
52
53     def request(self, method, url, fields=None, headers=None, **urlopen_kw):
54         """
55         Make a request using :meth:`urlopen` with the appropriate encoding of
56         ``fields`` based on the ``method`` used.
57
58         This is a convenience method that requires the least amount of manual
59         effort. It can be used in most situations, while still having the
60         option to drop down to more specific methods when necessary, such as
61         :meth:`request_encode_url`, :meth:`request_encode_body`,
62         or even the lowest level :meth:`urlopen`.
63         """
64         method = method.upper()
65
66         if method in self._encode_url_methods:
67             return self.request_encode_url(method, url, fields=fields,
68                                            headers=headers,
69                                            **urlopen_kw)
70         else:
71             return self.request_encode_body(method, url, fields=fields,
72                                             headers=headers,
73                                             **urlopen_kw)
74
75     def request_encode_url(self, method, url, fields=None, headers=None,
76                            **urlopen_kw):
77         """
78         Make a request using :meth:`urlopen` with the ``fields`` encoded in
79         the url. This is useful for request methods like GET, HEAD, DELETE, etc.
80         """
81         if headers is None:
82             headers = self.headers
83
84         extra_kw = {'headers': headers}
85         extra_kw.update(urlopen_kw)
86
87         if fields:
88             url += '?' + urlencode(fields)
89
90         return self.urlopen(method, url, **extra_kw)
91
92     def request_encode_body(self, method, url, fields=None, headers=None,
93                             encode_multipart=True, multipart_boundary=None,
94                             **urlopen_kw):
95         """
96         Make a request using :meth:`urlopen` with the ``fields`` encoded in
97         the body. This is useful for request methods like POST, PUT, PATCH, etc.
98
99         When ``encode_multipart=True`` (default), then
100         :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode
101         the payload with the appropriate content type. Otherwise
102         :meth:`urllib.urlencode` is used with the
103         'application/x-www-form-urlencoded' content type.
104
105         Multipart encoding must be used when posting files, and it's reasonably
106         safe to use it in other times too. However, it may break request
107         signing, such as with OAuth.
108
109         Supports an optional ``fields`` parameter of key/value strings AND
110         key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
111         the MIME type is optional. For example::
112
113             fields = {
114                 'foo': 'bar',
115                 'fakefile': ('foofile.txt', 'contents of foofile'),
116                 'realfile': ('barfile.txt', open('realfile').read()),
117                 'typedfile': ('bazfile.bin', open('bazfile').read(),
118                               'image/jpeg'),
119                 'nonamefile': 'contents of nonamefile field',
120             }
121
122         When uploading a file, providing a filename (the first parameter of the
123         tuple) is optional but recommended to best mimick behavior of browsers.
124
125         Note that if ``headers`` are supplied, the 'Content-Type' header will
126         be overwritten because it depends on the dynamic random boundary string
127         which is used to compose the body of the request. The random boundary
128         string can be explicitly set with the ``multipart_boundary`` parameter.
129         """
130         if headers is None:
131             headers = self.headers
132
133         extra_kw = {'headers': {}}
134
135         if fields:
136             if 'body' in urlopen_kw:
137                 raise TypeError(
138                     "request got values for both 'fields' and 'body', can only specify one.")
139
140             if encode_multipart:
141                 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)
142             else:
143                 body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'
144
145             extra_kw['body'] = body
146             extra_kw['headers'] = {'Content-Type': content_type}
147
148         extra_kw['headers'].update(headers)
149         extra_kw.update(urlopen_kw)
150
151         return self.urlopen(method, url, **extra_kw)