1 from __future__ import absolute_import
3 from urllib.parse import urlencode
5 from urllib import urlencode
7 from .filepost import encode_multipart_formdata
10 __all__ = ['RequestMethods']
13 class RequestMethods(object):
15 Convenience mixin for classes who implement a :meth:`urlopen` method, such
16 as :class:`~urllib3.connectionpool.HTTPConnectionPool` and
17 :class:`~urllib3.poolmanager.PoolManager`.
19 Provides behavior for making common types of HTTP request methods and
20 decides which type of request field encoding to use.
24 :meth:`.request_encode_url` is for sending requests whose fields are
25 encoded in the URL (such as GET, HEAD, DELETE).
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).
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
35 Initializer parameters:
38 Headers to include with all requests, unless other headers are given
42 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])
44 def __init__(self, headers=None):
45 self.headers = headers or {}
47 def urlopen(self, method, url, body=None, headers=None,
48 encode_multipart=True, multipart_boundary=None,
50 raise NotImplemented("Classes extending RequestMethods must implement "
51 "their own ``urlopen`` method.")
53 def request(self, method, url, fields=None, headers=None, **urlopen_kw):
55 Make a request using :meth:`urlopen` with the appropriate encoding of
56 ``fields`` based on the ``method`` used.
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`.
64 method = method.upper()
66 if method in self._encode_url_methods:
67 return self.request_encode_url(method, url, fields=fields,
71 return self.request_encode_body(method, url, fields=fields,
75 def request_encode_url(self, method, url, fields=None, headers=None,
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.
82 headers = self.headers
84 extra_kw = {'headers': headers}
85 extra_kw.update(urlopen_kw)
88 url += '?' + urlencode(fields)
90 return self.urlopen(method, url, **extra_kw)
92 def request_encode_body(self, method, url, fields=None, headers=None,
93 encode_multipart=True, multipart_boundary=None,
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.
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.
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.
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::
115 'fakefile': ('foofile.txt', 'contents of foofile'),
116 'realfile': ('barfile.txt', open('realfile').read()),
117 'typedfile': ('bazfile.bin', open('bazfile').read(),
119 'nonamefile': 'contents of nonamefile field',
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.
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.
131 headers = self.headers
133 extra_kw = {'headers': {}}
136 if 'body' in urlopen_kw:
138 "request got values for both 'fields' and 'body', can only specify one.")
141 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)
143 body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'
145 extra_kw['body'] = body
146 extra_kw['headers'] = {'Content-Type': content_type}
148 extra_kw['headers'].update(headers)
149 extra_kw.update(urlopen_kw)
151 return self.urlopen(method, url, **extra_kw)