urllib3 upgrade
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 85507dd · Browse files · 7 files·+357 added−144 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+357 added−144 removed
- other:+357 added−144 removed
Provenance
- Commit
8d4afcb- Tree
939b8ac- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
85507dd
7 files changed+357 added−144 removed
modified:requests/packages/urllib3/__init__.py+20 added-4 removed
6 unmodified lines7 """8 urllib3 - Thread-safe connection pooling and re-using.9 """10 11-__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"12-__license__ = "MIT"13-__version__ = "$Rev$"11+__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12+__license__ = 'MIT'13+__version__ = '1.0'14 15 16 from .connectionpool import (17 HTTPConnectionPool,8 unmodified lines26 MaxRetryError,27 SSLError,28 TimeoutError)29 30-from .poolmanager import PoolManager30+from .poolmanager import PoolManager, ProxyManager, proxy_from_url31 from .response import HTTPResponse32 from .filepost import encode_multipart_formdata33+34+35+# Set default logging handler to avoid "No handler found" warnings.36+import logging37+try:38+ from logging import NullHandler39+except ImportError:40+ class NullHandler(logging.Handler):41+ def emit(self, record):42+ pass43+44+logging.getLogger(__name__).addHandler(NullHandler())45+46+# ... Clean up.47+del logging48+del NullHandlermodified:requests/packages/urllib3/_collections.py+1 added-2 removed
103 unmodified lines104 105 # Discard invalid and excess entries106 self._prune_entries(len(self._container) - self._maxsize)107 108-108 def __delitem__(self, key):109 self._invalidate_entry(key)110 del self._container[key]111 del self._access_lookup[key]112 113 def __len__(self):115- return len(self.access_log)114+ return self._container.__len__()115 116 def __iter__(self):117 return self._container.__iter__()118 2 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+106 added-114 removed
6 unmodified lines7 import logging8 import socket9 10 11-from urllib import urlencode11 from httplib import HTTPConnection, HTTPSConnection, HTTPException12 from Queue import Queue, Empty, Full13 from select import select14 from socket import error as SocketError, timeout as SocketTimeout6 unmodified lines21 ssl = None22 BaseSSLError = None23 24 26-from .filepost import encode_multipart_formdata25+from .request import RequestMethods26 from .response import HTTPResponse27 from .exceptions import (28 SSLError,29 MaxRetryError,30 TimeoutError,31 HostChangedError,33- EmptyPoolError)32+ EmptyPoolError,33+)34 35 36 log = logging.getLogger(__name__)37 38 _Default = object()39 40 41-41 ## Connection objects (extension of httplib)42 43 class VerifiedHTTPSConnection(HTTPSConnection):44 """45 Based on httplib.HTTPSConnection but wraps the socket with46 SSL certification.47 """48+ cert_reqs = None49+ cert_reqs = None50 50- def __init__(self, **kwargs):51- HTTPSConnection.__init__(self, **kwargs)52- self.cert_reqs = None53- self.ca_certs = None54-51 def set_cert(self, key_file=None, cert_file=None,52 cert_reqs='CERT_NONE', ca_certs=None):53 ssl_req_scheme = {54 'CERT_NONE': ssl.CERT_NONE,19 unmodified lines74 75 ## Pool objects76 77 class ConnectionPool(object):78+ """79+ Base class for all connection pools, such as80+ :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.81+ """82 pass83 84 85-class HTTPConnectionPool(ConnectionPool):85+class HTTPConnectionPool(ConnectionPool, RequestMethods):86 """87 Thread-safe connection pool for one host.88 89- host89+ :param host:90 Host used for this HTTP Connection (e.g. "localhost"), passed into91- httplib.HTTPConnection()91+ :class:`httplib.HTTPConnection`.92 93- port93+ :param port:94 Port used for this HTTP Connection (None is equivalent to 80), passed95- into httplib.HTTPConnection()95+ into :class:`httplib.HTTPConnection`.96 97- strict97+ :param strict:98 Causes BadStatusLine to be raised if the status line can't be parsed99 as a valid HTTP/1.0 or 1.1 status line, passed into100- httplib.HTTPConnection()100+ :class:`httplib.HTTPConnection`.101 102- timeout102+ :param timeout:103 Socket timeout for each individual connection, can be a float. None104 disables timeout.105 106- maxsize106+ :param maxsize:107 Number of connections to save that can be reused. More than 1 is useful108 in multithreaded situations. If ``block`` is set to false, more109 connections will be created but they will not be saved once they've110 been used.111 112- block112+ :param block:113 If set to True, no more than ``maxsize`` connections will be used at114 a time. When no free connections are available, the call will block115 until a connection has been released. This is a useful side effect for116 particular multithreaded situations where one does not want to use more117 than maxsize connections per host to prevent flooding.118 119- headers119+ :param headers:120 Headers to include with all requests, unless other headers are given121 explicitly.122 """123 18 unmodified lines142 self.num_requests = 0143 144 def _new_conn(self):145 """146- Return a fresh HTTPConnection.146+ Return a fresh :class:`httplib.HTTPConnection`.147 """148 self.num_connections += 1149 log.info("Starting new HTTP connection (%d): %s" %150 (self.num_connections, self.host))1 unmodified line152 153 def _get_conn(self, timeout=None):154 """155 Get a connection. Will return a pooled connection if one is available.156+157+ If no connections are available and :prop:`.block` is ``False``, then a156- Otherwise, a fresh connection is returned.158+ fresh connection is returned.159+160+ :param timeout:161+ Seconds to wait before giving up and raising162+ :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and163+ :prop:`.block` is ``True``.164 """165 conn = None166 try:167 conn = self.pool.get(block=self.block, timeout=timeout)14 unmodified lines182 183 def _put_conn(self, conn):184 """185 Put a connection back into the pool.186+187+ :param conn:188+ Connection object for the current host and port as returned by189+ :meth:`._new_conn` or :meth:`._get_conn`.190+191 If the pool is already full, the connection is discarded because we192 exceeded maxsize. If connections are discarded frequently, then maxsize193 should be increased.194 """14 unmodified lines209 210 if timeout is _Default:211 timeout = self.timeout212 201-213 conn.request(method, url, **httplib_request_kw)214 conn.sock.settimeout(timeout)215 httplib_response = conn.getresponse()216 206-217 log.debug("\"%s %s %s\" %s %s" %218 (method, url,219 conn._http_vsn_str, # pylint: disable-msg=W0212220 httplib_response.status, httplib_response.length))1 unmodified line222 return httplib_response223 224 225 def is_same_host(self, url):226+ """227+ Check if the given ``url`` is a member of the same host as this228+ conncetion pool.229+ """230+ # TODO: Add optional support for socket.gethostbyname checking.231 return (url.startswith('/') or232 get_host(url) == (self.scheme, self.host, self.port))233 234 def urlopen(self, method, url, body=None, headers=None, retries=3,235 redirect=True, assert_same_host=True, timeout=_Default,236 pool_timeout=None, release_conn=None, **response_kw):237 """223- Get a connection from the pool and perform an HTTP request.238+ Get a connection from the pool and perform an HTTP request. This is the239+ lowest level call for making a request, so you'll need to specify all240+ the raw details.241 225- method242+ .. note::243+244+ More commonly, it's appropriate to use a convenience method provided245+ by :class:`.RequestMethods`, such as :meth:`.request`.246+247+ :param method:248 HTTP request method (such as GET, POST, PUT, etc.)249 228- body250+ :param body:251 Data to send in the request body (useful for creating252 POST requests, see HTTPConnectionPool.post_url for253 more convenience).254 233- headers255+ :param headers:256 Dictionary of custom headers to send, such as User-Agent,257 If-None-Match, etc. If None, pool headers are used. If provided,258 these headers completely replace any pool-specific headers.259 238- retries260+ :param retries:261 Number of retries to allow before raising262 a MaxRetryError exception.263 242- redirect264+ :param redirect:265 Automatically handle redirects (status codes 301, 302, 303, 307),266 each redirect counts as a retry.267 246- assert_same_host247- If True, will make sure that the host of the pool requests is268+ :param assert_same_host:269+ If ``True``, will make sure that the host of the pool requests is270 consistent else will raise HostChangedError. When False, you can271 use the pool on an HTTP proxy and request foreign hosts.272 251- timeout273+ :param timeout:274 If specified, overrides the default timeout for this one request.275 254- pool_timeout276+ :param pool_timeout:277 If set and the pool is set to block=True, then this method will278 block for ``pool_timeout`` seconds and raise EmptyPoolError if no279 connection is available within the time period.280 259- release_conn281+ :param release_conn:282 If False, then the urlopen call will not release the connection283 back into the pool once a response is received. This is useful if284 you're not preloading the response's content immediately. You will285 need to call ``r.release_conn()`` on the response ``r`` to return286 the connection back into the pool. If None, it takes the value of287 ``response_kw.get('preload_content', True)``.288 289+ :param \**response_kw:267- Additional parameters are passed to268- ``HTTPResponse.from_httplib(r, **response_kw)``290+ Additional parameters are passed to291+ :meth:`urllib3.response.HTTPResponse.from_httplib`292 """293 if headers is None:294 headers = self.headers295 17 unmodified lines313 try:314 # Request a connection from the queue315 # (Could raise SocketError: Bad file descriptor)316 conn = self._get_conn(timeout=pool_timeout)317+318 # Make the request on the httplib connection object319 httplib_response = self._make_request(conn, method, url,320 timeout=timeout,321 body=body, headers=headers)298- # print '!'322 323 # Import httplib's response into our own wrapper object324 response = HTTPResponse.from_httplib(httplib_response,325 pool=self,44 unmodified lines370 assert_same_host)371 372 return response373 351- def get_url(self, url, fields=None, headers=None, retries=3,352- redirect=True, **response_kw):353- """354- Wrapper for performing GET with urlopen (see urlopen for more details).374 356- Supports an optional ``fields`` dictionary parameter key/value strings.357- If provided, they will be added to the url.358- """359- if fields:360- url += '?' + urlencode(fields)361- return self.urlopen('GET', url, headers=headers, retries=retries,362- redirect=redirect, **response_kw)375+class HTTPSConnectionPool(HTTPConnectionPool):376+ """377+ Same as :class:`.HTTPConnectionPool`, but HTTPS.378 364- def post_url(self, url, fields=None, headers=None, retries=3,365- redirect=True, encode_multipart=True, multipart_boundary=None,366- **response_kw):367- """368- Wrapper for performing POST with urlopen (see urlopen369- for more details).379+ When Python is compiled with the :mod:`ssl` module, then380+ :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,381+ instead of :class:httplib.HTTPSConnection`.382 371- Supports an optional ``fields`` parameter of key/value strings AND372- key/filetuple. A filetuple is a (filename, data) tuple. For example:373-374- fields = {375- 'foo': 'bar',376- 'foofile': ('foofile.txt', 'contents of foofile'),377- }378-379- If encode_multipart=True (default), then380- ``urllib3.filepost.encode_multipart_formdata`` is used to encode the381- payload with the appropriate content type. Otherwise382- ``urllib.urlencode`` is used with 'application/x-www-form-urlencoded'383- content type.384-385- Multipart encoding must be used when posting files, and it's reasonably386- safe to use it other times too. It may break request signing, such as387- OAuth.388-389- NOTE: If ``headers`` are supplied, the 'Content-Type' value will be390- overwritten because it depends on the dynamic random boundary string391- which is used to compose the body of the request.392- """393- if encode_multipart:394- body, content_type = encode_multipart_formdata(fields or {},395- boundary=multipart_boundary)396- else:397- body, content_type = (398- urlencode(fields or {}),399- 'application/x-www-form-urlencoded')400-401- headers = headers or {}402- headers.update({'Content-Type': content_type})403-404- return self.urlopen('POST', url, body, headers=headers,405- retries=retries, redirect=redirect, **response_kw)406-407-408-class HTTPSConnectionPool(HTTPConnectionPool):383+ The ``key_file``, ``cert_file``, ``cert_reqs``, and ``ca_certs`` parameters384+ are only used if :mod:`ssl` is available and are fed into385+ :meth:`ssl.wrap_socket` to upgrade the connection socket into an SSL socket.386 """410- Same as HTTPConnectionPool, but HTTPS.411- """387 388 scheme = 'https'389 390 def __init__(self, host, port=None,391 strict=False, timeout=None, maxsize=1,392 block=False, headers=None,393 key_file=None, cert_file=None,419- cert_reqs=ssl.CERT_REQUIRED, ca_certs=None):394+ cert_reqs='CERT_NONE', ca_certs=None):395 396 super(HTTPSConnectionPool, self).__init__(host, port,397 strict, timeout, maxsize,398 block, headers)3 unmodified lines402 self.ca_certs = ca_certs403 404 def _new_conn(self):405 """431- Return a fresh HTTPSConnection.406+ Return a fresh :class:`httplib.HTTPSConnection`.407 """433-408 self.num_connections += 1409 log.info("Starting new HTTPS connection (%d): %s"410 % (self.num_connections, self.host))411 12 unmodified lines424 basic_auth=None):425 """426 Shortcuts for generating request headers.427 454- keep_alive455- If true, adds 'connection: keep-alive' header.428+ :param keep_alive:429+ If ``True``, adds 'connection: keep-alive' header.430 457- accept_encoding431+ :param accept_encoding:432 Can be a boolean, list, or string.459- True translates to 'gzip,deflate'.433+ ``True`` translates to 'gzip,deflate'.434 List will get joined by comma.435 String will be used as provided.436 463- user_agent437+ :param user_agent:438 String representing the user-agent you want, such as439 "python-urllib3/0.6"440 467- basic_auth441+ :param basic_auth:442 Colon-separated username:password string for 'authorization: basic ...'443 auth header.444+445+ Example: ::446+447+ >>> make_headers(keep_alive=True, user_agent="Batman/1.0")448+ {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}449+ >>> make_headers(accept_encoding=True)450+ {'accept-encoding': 'gzip,deflate'}451 """452 headers = {}453 if accept_encoding:454 if isinstance(accept_encoding, str):20 unmodified lines475 def get_host(url):476 """477 Given a url, return its scheme, host and port (None if it's not there).478 498- For example:499- >>> get_host('http://google.com/mail/')500- http, google.com, None501- >>> get_host('google.com:80')502- http, google.com, 80479+ For example: ::480+481+ >>> get_host('http://google.com/mail/')482+ ('http', 'google.com', None)483+ >>> get_host('google.com:80')484+ ('http', 'google.com', 80)485 """486 # This code is actually similar to urlparse.urlsplit, but much487 # simplified for our needs.488 port = None9 unmodified lines498 499 500 def connection_from_url(url, **kw):501 """520- Given a url, return an HTTP(S)ConnectionPool instance of its host.502+ Given a url, return an :class:`.ConnectionPool` instance of its host.503 522- This is a shortcut for not having to determine the host of the url523- before creating an HTTP(S)ConnectionPool instance.504+ This is a shortcut for not having to parse out the scheme, host, and port505+ of the url before creating an :class:`.ConnectionPool` instance.506 525- Passes on whatever kw arguments to the constructor of526- HTTP(S)ConnectionPool. (e.g. timeout, maxsize, block)507+ :param url:508+ Absolute URL string that must include the scheme. Port is optional.509+510+ :param \**kw:511+ Passes additional parameters to the constructor of the appropriate512+ :class:`.ConnectionPool`. Useful for specifying things like513+ timeout, maxsize, headers, etc.514+515+ Example: ::516+517+ >>> conn = connection_from_url('http://google.com/')518+ >>> r = conn.request('GET', '/')519 """520 scheme, host, port = get_host(url)521 if scheme == 'https':522 return HTTPSConnectionPool(host, port=port, **kw)2 unmodified linesmodified:requests/packages/urllib3/filepost.py+13 added
20 unmodified lines21 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'22 23 24 def encode_multipart_formdata(fields, boundary=None):25+ """26+ Encode a dictionary of ``fields`` using the multipart/form-data mime format.27+28+ :param fields:29+ Dictionary of fields. The key is treated as the field name, and the30+ value as the body of the form-data. If the value is a tuple of two31+ elements, then the first element is treated as the filename of the32+ form-data section.33+34+ :param boundary:35+ If not specified, then a random boundary will be generated using36+ :func:`mimetools.choose_boundary`.37+ """38 body = StringIO()39 if boundary is None:40 boundary = mimetools.choose_boundary()41 30 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+62 added-15 removed
3 unmodified lines4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 from ._collections import RecentlyUsedContainer8-from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, get_host8+from .connectionpool import (9+ HTTPConnectionPool, HTTPSConnectionPool,10+ get_host, connection_from_url,11+)12 13 14+__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']15+16+17+from .request import RequestMethods18+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool19+20+21 pool_classes_by_scheme = {22 'http': HTTPConnectionPool,23 'https': HTTPSConnectionPool,24 }3 unmodified lines28 'https': 443,29 }30 31 22-class PoolManager(object):32+class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.36 27- num_pools37+ :param num_pools:38 Number of connection pools to cache before discarding the least recently39 used pool.40 41+ :param \**connection_pool_kw:31- Additional parameters are used to create fresh ConnectionPool instances.42+ Additional parameters are used to create fresh43+ :class:`urllib3.connectionpool.ConnectionPool` instances.44 45+ Example: ::46+47+ >>> manager = PoolManager()48+ >>> r = manager.urlopen("http://google.com/")49+ >>> r = manager.urlopen("http://google.com/mail")50+ >>> r = manager.urlopen("http://yahoo.com/")51+ >>> len(r.pools)52+ 253+54 """55 56 # TODO: Make sure there are no memory leaks here.57 58 def __init__(self, num_pools=10, **connection_pool_kw):59 self.connection_pool_kw = connection_pool_kw39-60 self.pools = RecentlyUsedContainer(num_pools)41- self.recently_used_pools = []61 62 def connection_from_host(self, host, port=80, scheme='http'):63 """45- Get a ConnectionPool based on the host, port, and scheme.64+ Get a :class:`ConnectionPool` based on the host, port, and scheme.65+66+ Note that an appropriate ``port`` value is required here to normalize67+ connection pools in our container most effectively.68 """69 pool_key = (scheme, host, port)70 49-71 # If the scheme, host, or port doesn't match existing open connections,72 # open a new ConnectionPool.73 pool = self.pools.get(pool_key)74 if pool:8 unmodified lines83 return pool84 85 def connection_from_url(self, url):86 """66- Similar to connectionpool.connection_from_url but doesn't pass any67- additional keywords to the ConnectionPool constructor. Additional68- keywords are taken from the PoolManager constructor.87+ Similar to :func:`urllib3.connectionpool.connection_from_url` but88+ doesn't pass any additional parameters to the89+ :class:`urllib3.connectionpool.ConnectionPool` constructor.90+91+ Additional parameters are taken from the :class:`.PoolManager`92+ constructor.93 """94 scheme, host, port = get_host(url)95 96 port = port or port_by_scheme.get(scheme, 80)97 74- r = self.connection_from_host(host, port=port, scheme=scheme)98+ return self.connection_from_host(host, port=port, scheme=scheme)99 76- return r100+ def urlopen(self, method, url, **kw):101+ """102+ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.103 104+ ``url`` must be absolute, such that an appropriate105+ :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.106+ """107+ conn = self.connection_from_url(url)108+ return conn.urlopen(method, url, assert_same_host=False, **kw)109+110+111+class ProxyManager(object):112+ """113+ Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method114+ will make requests to any url through the defined proxy.115+ """116+117+ def __init__(self, proxy_pool):118+ self.proxy_pool = proxy_pool119+120 def urlopen(self, method, url, **kw):121 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."80- conn = self.connection_from_url(url)81- return conn.urlopen(method, url, **kw)122+ kw['assert_same_host'] = False123+ return self.proxy_pool.urlopen(method, url, **kw)124+125+126+def proxy_from_url(url, **pool_kw):127+ proxy_pool = connection_from_url(url, **pool_kw)128+ return ProxyManager(proxy_pool)added:requests/packages/urllib3/request.py+145 added
1+# urllib3/request.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+8+from urllib import urlencode9+10+from .filepost import encode_multipart_formdata11+12+13+__all__ = ['RequestMethods']14+15+16+class RequestMethods(object):17+ """18+ Convenience mixin for classes who implement a :meth:`urlopen` method, such19+ as :class:`~urllib3.connectionpool.HTTPConnectionPool` and20+ :class:`~urllib3.poolmanager.PoolManager`.21+22+ Provides behavior for making common types of HTTP request methods and23+ decides which type of request field encoding to use.24+25+ Specifically,26+27+ :meth:`.request_encode_url` is for sending requests whose fields are encoded28+ in the URL (such as GET, HEAD, DELETE).29+30+ :meth:`.request_encode_body` is for sending requests whose fields are31+ encoded in the *body* of the request using multipart or www-orm-urlencoded32+ (such as for POST, PUT, PATCH).33+34+ :meth:`.request` is for making any kind of request, it will look up the35+ appropriate encoding format and use one of the above two methods to make36+ the request.37+ """38+39+ _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])40+41+ _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])42+43+ def urlopen(self, method, url, body=None, headers=None,44+ encode_multipart=True, multipart_boundary=None,45+ **kw):46+ raise NotImplemented("Classes extending RequestMethods must implement "47+ "their own ``urlopen`` method.")48+49+ def request(self, method, url, fields=None, headers=None, **urlopen_kw):50+ """51+ Make a request using :meth:`urlopen` with the appropriate encoding of52+ ``fields`` based on the ``method`` used.53+54+ This is a convenience method that requires the least amount of manual55+ effort. It can be used in most situations, while still having the option56+ to drop down to more specific methods when necessary, such as57+ :meth:`request_encode_url`, :meth:`request_encode_body`,58+ or even the lowest level :meth:`urlopen`.59+ """60+ method = method.upper()61+62+ if method in self._encode_url_methods:63+ return self.request_encode_url(method, url, fields=fields,64+ headers=headers,65+ **urlopen_kw)66+ else:67+ return self.request_encode_body(method, url, fields=fields,68+ headers=headers,69+ **urlopen_kw)70+71+ def request_encode_url(self, method, url, fields=None, **urlopen_kw):72+ """73+ Make a request using :meth:`urlopen` with the ``fields`` encoded in74+ the url. This is useful for request methods like GET, HEAD, DELETE, etc.75+ """76+ if fields:77+ url += '?' + urlencode(fields)78+ return self.urlopen(method, url, **urlopen_kw)79+80+ def request_encode_body(self, method, url, fields=None, headers=None,81+ encode_multipart=True, multipart_boundary=None,82+ **urlopen_kw):83+ """84+ Make a request using :meth:`urlopen` with the ``fields`` encoded in85+ the body. This is useful for request methods like POST, PUT, PATCH, etc.86+87+ When ``encode_multipart=True`` (default), then88+ :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the89+ payload with the appropriate content type. Otherwise90+ :meth:`urllib.urlencode` is used with the91+ 'application/x-www-form-urlencoded' content type.92+93+ Multipart encoding must be used when posting files, and it's reasonably94+ safe to use it in other times too. However, it may break request signing,95+ such as with OAuth.96+97+ Supports an optional ``fields`` parameter of key/value strings AND98+ key/filetuple. A filetuple is a (filename, data) tuple. For example: ::99+100+ fields = {101+ 'foo': 'bar',102+ 'fakefile': ('foofile.txt', 'contents of foofile'),103+ 'realfile': ('barfile.txt', open('realfile').read()),104+ 'nonamefile': ('contents of nonamefile field'),105+ }106+107+ When uploading a file, providing a filename (the first parameter of the108+ tuple) is optional but recommended to best mimick behavior of browsers.109+110+ Note that if ``headers`` are supplied, the 'Content-Type' header will be111+ overwritten because it depends on the dynamic random boundary string112+ which is used to compose the body of the request. The random boundary113+ string can be explicitly set with the ``multipart_boundary`` parameter.114+ """115+ if encode_multipart:116+ body, content_type = encode_multipart_formdata(fields or {},117+ boundary=multipart_boundary)118+ else:119+ body, content_type = (urlencode(fields or {}),120+ 'application/x-www-form-urlencoded')121+122+ headers = headers or {}123+ headers.update({'Content-Type': content_type})124+125+ return self.urlopen(method, url, body=body, headers=headers,126+ **urlopen_kw)127+128+ # Deprecated:129+130+ def get_url(self, url, fields=None, **urlopen_kw):131+ """132+ .. deprecated:: 1.0133+ Use :meth:`request` instead.134+ """135+ return self.request_encode_url('GET', url, fields=fields,136+ **urlopen_kw)137+138+ def post_url(self, url, fields=None, headers=None, **urlopen_kw):139+ """140+ .. deprecated:: 1.0141+ Use :meth:`request` instead.142+ """143+ return self.request_encode_body('POST', url, fields=fields,144+ headers=headers,145+ **urlopen_kw)modified:requests/packages/urllib3/response.py+10 added-9 removed
40 unmodified lines41 loaded and decoded on-demand when the ``data`` property is accessed.42 43 Extra parameters for behaviour not present in httplib.HTTPResponse:44 45- preload_content45+ :param preload_content:46 If True, the response's body will be preloaded during construction.47 48- decode_content48+ :param decode_content:49 If True, attempts to decode specific content-encoding's based on headers50 (like 'gzip' and 'deflate') will be skipped and raw data will be used51 instead.52 53- original_response53+ :param original_response:54 When this HTTPResponse wrapper is generated from an httplib.HTTPResponse55 object, it's convenient to include the original for debug purposes. It's56 otherwise unused.57 """44 unmodified lines102 cache_content=True)103 104 def read(self, amt=None, decode_content=True, cache_content=False):105 """106- Similar to ``httplib.HTTPResponse.read(amt=None)``.106+ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional107+ parameters: ``decode_content`` and ``cache_content``.108 108- amt109+ :param amt:110 How much of the content to read. If specified, decoding and caching111 is skipped because we can't decode partial content nor does it make112 sense to cache partial content as the full response.113 113- decode_content114+ :param decode_content:115 If True, will attempt to decode the body based on the116 'content-encoding' header. (Overridden if ``amt`` is set.)117 117- cache_content118+ :param cache_content:119 If True, will save the returned data such that the same result is120 returned despite of the state of the underlying file object. This121 is useful if you want the ``.data`` property to continue working122 after having ``.read()`` the file object. (Overridden if ``amt`` is33 unmodified lines156 157 @staticmethod158 def from_httplib(r, **response_kw):159 """159- Given an httplib.HTTPResponse instance ``r``, return a corresponding160- urllib3.HTTPResponse object.160+ Given an :class:`httplib.HTTPResponse` instance ``r``, return a161+ corresponding :class:`urllib3.response.HTTPResponse` object.162 163 Remaining parameters are passed to the HTTPResponse constructor, along164 with ``original_response=r``.165 """16 unmodified lines