2 # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
4 # This module is part of urllib3 and is released under
5 # the MIT License: http://www.opensource.org/licenses/mit-license.php
8 from urllib.parse import urlencode
10 from urllib import urlencode
12 from .filepost import encode_multipart_formdata
15 __all__ = ['RequestMethods']
18 class RequestMethods(object):
20 Convenience mixin for classes who implement a :meth:`urlopen` method, such
21 as :class:`~urllib3.connectionpool.HTTPConnectionPool` and
22 :class:`~urllib3.poolmanager.PoolManager`.
24 Provides behavior for making common types of HTTP request methods and
25 decides which type of request field encoding to use.
29 :meth:`.request_encode_url` is for sending requests whose fields are encoded
30 in the URL (such as GET, HEAD, DELETE).
32 :meth:`.request_encode_body` is for sending requests whose fields are
33 encoded in the *body* of the request using multipart or www-form-urlencoded
34 (such as for POST, PUT, PATCH).
36 :meth:`.request` is for making any kind of request, it will look up the
37 appropriate encoding format and use one of the above two methods to make
40 Initializer parameters:
43 Headers to include with all requests, unless other headers are given
47 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])
48 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])
50 def __init__(self, headers=None):
51 self.headers = headers or {}
53 def urlopen(self, method, url, body=None, headers=None,
54 encode_multipart=True, multipart_boundary=None,
56 raise NotImplementedError("Classes extending RequestMethods must implement "
57 "their own ``urlopen`` method.")
59 def request(self, method, url, fields=None, headers=None, **urlopen_kw):
61 Make a request using :meth:`urlopen` with the appropriate encoding of
62 ``fields`` based on the ``method`` used.
64 This is a convenience method that requires the least amount of manual
65 effort. It can be used in most situations, while still having the option
66 to drop down to more specific methods when necessary, such as
67 :meth:`request_encode_url`, :meth:`request_encode_body`,
68 or even the lowest level :meth:`urlopen`.
70 method = method.upper()
72 if method in self._encode_url_methods:
73 return self.request_encode_url(method, url, fields=fields,
77 return self.request_encode_body(method, url, fields=fields,
81 def request_encode_url(self, method, url, fields=None, **urlopen_kw):
83 Make a request using :meth:`urlopen` with the ``fields`` encoded in
84 the url. This is useful for request methods like GET, HEAD, DELETE, etc.
87 url += '?' + urlencode(fields)
88 return self.urlopen(method, url, **urlopen_kw)
90 def request_encode_body(self, method, url, fields=None, headers=None,
91 encode_multipart=True, multipart_boundary=None,
94 Make a request using :meth:`urlopen` with the ``fields`` encoded in
95 the body. This is useful for request methods like POST, PUT, PATCH, etc.
97 When ``encode_multipart=True`` (default), then
98 :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the
99 payload with the appropriate content type. Otherwise
100 :meth:`urllib.urlencode` is used with the
101 'application/x-www-form-urlencoded' content type.
103 Multipart encoding must be used when posting files, and it's reasonably
104 safe to use it in other times too. However, it may break request signing,
107 Supports an optional ``fields`` parameter of key/value strings AND
108 key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
109 the MIME type is optional. For example: ::
113 'fakefile': ('foofile.txt', 'contents of foofile'),
114 'realfile': ('barfile.txt', open('realfile').read()),
115 'typedfile': ('bazfile.bin', open('bazfile').read(),
117 'nonamefile': 'contents of nonamefile field',
120 When uploading a file, providing a filename (the first parameter of the
121 tuple) is optional but recommended to best mimick behavior of browsers.
123 Note that if ``headers`` are supplied, the 'Content-Type' header will be
124 overwritten because it depends on the dynamic random boundary string
125 which is used to compose the body of the request. The random boundary
126 string can be explicitly set with the ``multipart_boundary`` parameter.
129 body, content_type = encode_multipart_formdata(fields or {},
130 boundary=multipart_boundary)
132 body, content_type = (urlencode(fields or {}),
133 'application/x-www-form-urlencoded')
136 headers = self.headers
138 headers_ = {'Content-Type': content_type}
139 headers_.update(headers)
141 return self.urlopen(method, url, body=body, headers=headers_,