Skip to content
Myr

Merge branch 'develop'

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 · parents 72943d0, 9aa62d5 · Browse files · 37 files+2173 added−1022 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

37 files+2173 added−1022 removed

  • other:+2173 added−1022 removed

37 files+2173 added−1022 removed

modified:docs/_themes/kr/static/flasky.css_t+91 added-1 removed
385 unmodified lines
386 background: #EEE;387}388389390@media screen and (max-width: 600px) {390@media screen and (max-width: 870px) {391392 div.sphinxsidebar {393 display: none;394 }
40 unmodified lines
435 .github {436 display: none;437 }438439440441}442443444445@media screen and (max-width: 875px) {446447 body {448 margin: 0;449 padding: 20px 30px;450 }451452 div.documentwrapper {453 float: none;454 background: white;455 }456457 div.sphinxsidebar {458 display: block;459 float: none;460 width: 102.5%;461 margin: 50px -30px -20px -30px;462 padding: 10px 20px;463 background: #333;464 color: white;465 }466467 div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,468 div.sphinxsidebar h3 a {469 color: white;470 }471472 div.sphinxsidebar a {473 color: #aaa;474 }475476 div.sphinxsidebar p.logo {477 display: none;478 }479480 div.document {481 width: 100%;482 margin: 0;483 }484485 div.related {486 display: block;487 margin: 0;488 padding: 10px 0 20px 0;489 }490491 div.related ul,492 div.related ul li {493 margin: 0;494 padding: 0;495 }496497 div.footer {498 display: none;499 }500501 div.bodywrapper {502 margin: 0;503 }504505 div.body {506 min-height: 0;507 padding: 0;508 }509510 .rtd_doc_footer {511 display: none;512 }513514 .document {515 width: auto;516 }517518 .footer {519 width: auto;520 }521522 .footer {523 width: auto;524 }525526 .github {527 display: none;528 }529}530531532/* scrollbars */533534::-webkit-scrollbar {535 width: 6px;
35 unmodified lines
deleted:docs/_themes/kr/static/small_flask.css-90 removed
1/*2 * small_flask.css_t3 * ~~~~~~~~~~~~~~~~~4 *5 * :copyright: Copyright 2010 by Armin Ronacher.6 * :license: Flask Design License, see LICENSE for details.7 */89body {10 margin: 0;11 padding: 20px 30px;12}1314div.documentwrapper {15 float: none;16 background: white;17}1819div.sphinxsidebar {20 display: block;21 float: none;22 width: 102.5%;23 margin: 50px -30px -20px -30px;24 padding: 10px 20px;25 background: #333;26 color: white;27}2829div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,30div.sphinxsidebar h3 a {31 color: white;32}3334div.sphinxsidebar a {35 color: #aaa;36}3738div.sphinxsidebar p.logo {39 display: none;40}4142div.document {43 width: 100%;44 margin: 0;45}4647div.related {48 display: block;49 margin: 0;50 padding: 10px 0 20px 0;51}5253div.related ul,54div.related ul li {55 margin: 0;56 padding: 0;57}5859div.footer {60 display: none;61}6263div.bodywrapper {64 margin: 0;65}6667div.body {68 min-height: 0;69 padding: 0;70}7172.rtd_doc_footer {73 display: none;74}7576.document {77 width: auto;78}7980.footer {81 width: auto;82}8384.footer {85 width: auto;86}8788.github {89 display: none;90}
modified:docs/_themes/kr/layout.html-2 removed
modified:docs/community/faq.rst+1 added-1 removed
71 unmodified lines
7273Keep-alive Support?74-------------------7576It's on the way.76Yep!777879Proxy Support?80--------------
3 unmodified lines
modified:docs/community/out-there.rst+1 added-1 removed
1Modules2=======34- `requests-oauth-hook <https://github.com/maraujop/requests-oauth-hook>`_, adds OAuth support to Requests.4- `requests-oauth <https://github.com/maraujop/requests-oauth>`_, adds OAuth support to Requests.5- `FacePy <https://github.com/jgorset/facepy>`_, a Python wrapper to the Facebook API.6- `robotframework-requests <https://github.com/bulkan/robotframework-requests>`_, a Robot Framework API wrapper.7- `fullerene <https://github.com/bitprophet/fullerene>`_, a Graphite Dashboard.8- `urbanairship-python <https://github.com/benjaminws/urbanairship-python>`_, a fork of the Urban Airship API wrapper.
58 unmodified lines
modified:docs/user/advanced.rst+58 added-9 removed
8 unmodified lines
9Session Objects10---------------1112The Session object allows you to persist certain parameters across13requests. It also establishes a CookieJar and passes it along14to any requests made from the Session instance.13requests. It also perstists cookies across all requests made from the14Session instance.1516A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::
17 unmodified lines
36 # both 'x-test' and 'x-test2' are sent37 c.get('http://httpbin.org/headers', headers={'x-test2': 'true'})383940.. admonition:: Global Settings40Any dictionaries that you pass to a request method will be merged with the session-level values that are set. The method-level parameters override session parameters.4142 Certain parameters are best set in the ``config`` dictionary43 (e.g. user agent header).42.. admonition:: Remove a Value From a Dict Parameter4344 Sometimes you'll want to omit session-level keys from a dict parameter. To do this, you simply set that key's value to ``None`` in the method-level parameter. It will automatically be omitted.4546All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.474849Body Content Workflow50----------------------5152By default, When you make a request, the body of the response isn't downloaded immediately. The response headers are downloaded when you make a request, but the content isn't downloaded until you access the :class:`Response.content` attribute.5354Let's walk through it::5556 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'57 r = requests.get(tarball_url)5859The request has been made, but the connection is still open. The response body has not been downloaded yet. ::6061 r.content6263The content has been downloaded and cached.6465You can override this default behavior with the ``prefetch`` parameter::6667 r = requests.get(tarball_url, prefetch=True)68 # Blocks until all of request body has been downloaded.697071Configuring Requests72--------------------7374Sometimes you may want to configure a request to customize it's behavior. To do75this, you can pass in a ``config`` dictionary to a request or session. See the :ref:`Configuration API Docs <configurations>` to learn more.767778Keep-Alive79----------8081Excellent news — thanks to urllib3. keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!8283If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::8485 s = requests.session()86 s.config['keep_alive'] = False878889Asynchronous Requests90----------------------9149Requests has first-class support for non-blocking i/o requests, powered92Requests has first-class support for concurrent requests, powered93by gevent. This allows you to send a bunch of HTTP requests at the same9495First, let's import the async module. Heads up — if you don't have53`gevent <gevent>`_ this will fail::96`gevent <http://pypi.python.org/pypi/gevent>`_ this will fail::9798 from requests import async99100The ``async`` module has the exact same api as ``requests``, except it
18 unmodified lines
119120 >>> async.map(rs)121 [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]122123.. admonition:: Throttling124125 The ``map`` function also takes a ``size`` parameter, that specifies the nubmer of connections to make at a time::126127 async.map(rs, size=5)128129130Event Hooks131-----------132133Requests has a hook system that you can use to manipulate portions of
113 unmodified lines
247by your application, you can turn on verbose logging.248249To do so, just configure Requests with a stream to write to::250202 >>> requests.settings.verbose = sys.stderr203 >>> requests.get('http://httpbin.org/headers')251 >>> my_config = {'verbose': sys.stderr}252 >>> requests.get('http://httpbin.org/headers', config=my_config)253 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers254 <Response [200]>
modified:docs/user/quickstart.rst+165 added-11 removed
37 unmodified lines
3839 >>> r.content40 '[{"repository":{"open_issues":0,"url":"https://github.com/...4142Requests does its best to decode content from the server. Most unicode charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.434445Make a POST Request46-------------------4748POST requests are equally simple::4950 r = requests.post("http://httpbin.org/post")515253Typically, you want to send some form-encoded data — much like an HTML form.54To do this, simply pass a dictionary to the `data` argument. Your dictionary of data will automatically be form-encoded when the request is made::5556 >>> payload = {'key1': 'value1', 'key2': 'value2'}57 >>> r = requests.post("http://httpbin.org/post", data=payload)58 >>> print r.content59 {60 "origin": "179.13.100.4",61 "files": {},62 "form": {63 "key2": "value2",64 "key1": "value1"65 },66 "url": "http://httpbin.org/post",67 "args": {},68 "headers": {69 "Content-Length": "23",70 "Accept-Encoding": "identity, deflate, compress, gzip",71 "Accept": "*/*",72 "User-Agent": "python-requests/0.8.0",73 "Host": "127.0.0.1:7077",74 "Content-Type": "application/x-www-form-urlencoded"75 },76 "data": ""77 }7879There are many times that you want to send data that is not form-encoded. If you pass in a ``string`` instead of a ``dict``, that data will be posted directly.8081For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8283 url = 'https://api.github.com/some/endpoint'84 payload = {'some': 'data'}8586 r = requests.post(url, data=json.dumps(payload))878889Custom Headers90--------------9192If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the93``headers`` parameter.9495For example, we didn't specify our content-type in the previous example::9697 url = 'https://api.github.com/some/endpoint'98 payload = {'some': 'data'}99 headers = {'content-type': 'application/json'}100101 r = requests.post(url, data=json.dumps(payload), headers=headers)102103104POST a Multipart-Encoded File105-----------------------------106107Requests makes it simple to upload Multipart-encoded files::108109 >>> url = 'http://httpbin.org/post'110 >>> files = {'report.xls': open('report.xls', 'rb')}111112 >>> r = requests.post(url, files=files)113 >>> r.content114 {115 "origin": "179.13.100.4",116 "files": {117 "hmm": "<censored...binary...data>"118 },119 "form": {},120 "url": "http://httpbin.org/post",121 "args": {},122 "headers": {123 "Content-Length": "3196",124 "Accept-Encoding": "identity, deflate, compress, gzip",125 "Accept": "*/*",126 "User-Agent": "python-requests/0.8.0",127 "Host": "httpbin.org:80",128 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"129 },130 "data": ""131 }132133134135Response Status Codes136---------------------137138We can check the response status code::
6 unmodified lines
145146 >>> r.status_code == requests.codes.ok147 True14857If we made a bad request, we can raise it with149If we made a bad request (non-200 response), we can raise it with150:class:`Response.raise_for_status()`::151152 >>> _r = requests.get('http://httpbin.org/status/404')153 >>> _r.status_code
59 unmodified lines
213214 >>> print r.cookies215 {'requests-is': 'awesome'}216125The underlying CookieJar is also available for more advanced handling::126127 >>> r.request.cookiejar128 <cookielib.CookieJar>129217To send your own cookies to the server, you can use the ``cookies``218parameter::219220 >>> url = 'http://httpbin.org/cookies'
7 unmodified lines
228Basic Authentication229--------------------230231Most web services require authentication. There many different types of145authentication, but the most common is called HTTP Basic Auth.232authentication, but the most common is HTTP Basic Auth.233147Making requests with Basic Auth is easy, with Requests::234Making requests with Basic Auth is extremely simple::235236 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))237 <Response [200]>238239240Digest Authentication241---------------------242156Another popular form of protecting web service is Digest Authentication.243Another popular form of web service protection is Digest Authentication::244158Requests supports it!::159245 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'246 >>> requests.get(url, auth=('digest', 'user', 'pass'))247 <Response [200]>248249250Redirection and History251-----------------------252253Requests will automatically perform location redirection while using impodotent methods.254255GitHub redirects all HTTP requests to HTTPS. Let's see what happens::256257 >>> r = request.get('http://github.com')258 >>> r.url259 'https://github.com/'260 >>> r.status_code261 200262 >>> r.history263 [<Response [301]>]264265The :class:`Response.history` list contains a list of the266:class:`Request` objects that were created in order to complete the request.267268If you're using GET, HEAD, or OPTIONS, you can disable redirection269handling with the ``disable_redirects`` parameter::270271 >>> r = request.get('http://github.com')272 >>> r.status_code273 301274 >>> r.history275 []276277If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::278279 >>> r = request.post('http://github.com')280 >>> r.url281 'https://github.com/'282 >>> r.history283 [<Response [301]>]284285286Timeouts287--------288289You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::290291 >>> requests.get('http://github.com', timeout=0.001)292 Traceback (most recent call last):293 File "<stdin>", line 1, in <module>294 requests.exceptions.Timeout: Request timed out.295296.. admonition:: Note297298 ``timeout`` only effects the connection process itself, not the downloading of the respone body.299300301Note302303Errors and Exceptions304---------------------305306In the event of a network problem (e.g. DNS failure, refused connection, etc),307Requests will raise a :class:`ConnectionError` exception.308309In the event of the rare invalid HTTP response, Requests will raise310an :class:`HTTPError` exception.311312If a request times out, a :class:`Timeout` exception is raised.313314If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.315316All exceptions that Requests explicitly raises inherit from317:class:`requests.exceptions.RequestException`.318319-----------------------320321Ready for more? Check out the :ref:`advanced <advanced>` section.
modified:docs/api.rst+57 added-18 removed
15 unmodified lines
16All of Request's functionality can be accessed by these 7 methods.17They all return an instance of the :class:`Response <Response>` object.1819.. autofunction:: request2021---------------------222324.. autoclass:: Response25 :inherited-members:2627---------------------2829.. autofunction:: head30.. autofunction:: get31.. autofunction:: post32.. autofunction:: put33.. autofunction:: patch34.. autofunction:: delete353628-----------37-----------------3839.. autofunction:: session4031.. autoclass:: Response32 :inherited-members:414243Exceptions44~~~~~~~~~~4546.. module:: requests4748.. autoexception:: RequestException49.. autoexception:: ConnectionError50.. autoexception:: HTTPError51.. autoexception:: URLRequired52.. autoexception:: TooManyRedirects535455.. _configurations:5657Configurations58--------------5960.. automodule:: requests.defaults616263.. _async:6465Async66-----6768.. module:: requests.async
17 unmodified lines
86Requests.8788.. module:: requests.utils8990Status Code Lookup91~~~~~~~~~~~~~~~~~~9293.. autofunction:: requests.codes9495::9697 >>> requests.codes['temporary_redirect']98 30199100 >>> requests.codes.teapot101 416102103 >>> requests.codes['\o/']104 416105106Cookies107~~~~~~~108109.. autofunction:: dict_from_cookiejar
16 unmodified lines
126These items are an internal component to Requests, and should never be127seen by the end user (developer). This part of the API documentation128exists for those who are extending the functionality of Requests.12983Exceptions84~~~~~~~~~~13086.. module:: requests8788.. autoexception:: HTTPError8990.. autoexception:: RequestException9192.. autoexception:: AuthenticationError93.. autoexception:: URLRequired94.. autoexception:: InvalidMethod95.. autoexception:: TooManyRedirects969798131Classes132~~~~~~~133134.. autoclass:: requests.Response135 :inherited-members:136137.. autoclass:: requests.Request138 :inherited-members:139140.. _sessionapi:141142.. autoclass:: requests.Session143 :inherited-members:144
modified:docs/index.rst+2 added-3 removed
31 unmodified lines
3233Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,34**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,35multipart files, and parameters with simple Python dictionaries, and access the36response data in the same way. It's powered by :py:class:`urllib2`, but it does37all the hard work and crazy hacks for you.36response data in the same way. It's powered by :py:class:`httplib` and :py:class:`urllib3`, and it strives to be as elegant and approachable as possible.3738Testimonials39------------4041`The Washington Post <http://www.washingtonpost.com/>`_, `Twitter, Inc <http://twitter.com>`_,42a U.S. Federal Institution,44NIH, 43NIH,44`Readability <http://readability.com>`_, and45`Work for Pie <http://workforpie.com>`_46use Requests internally.47
70 unmodified lines
deleted:requests/packages/poster/__init__.py-34 removed
1# Copyright (c) 2010 Chris AtLee2# 3# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to deal5# in the Software without restriction, including without limitation the rights6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7# copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:9# 10# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.12# 13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19# THE SOFTWARE.20"""poster module2122Support for streaming HTTP uploads, and multipart/form-data encoding2324```poster.version``` is a 3-tuple of integers representing the version number.25New releases of poster will always have a version number that compares greater26than an older version of poster.27New in version 0.6."""2829from __future__ import absolute_import3031from . import streaminghttp32from . import encode3334version = (0, 8, 0) # Thanks JP!
deleted:requests/packages/poster/encode.py-414 removed
1"""multipart/form-data encoding module23This module provides functions that faciliate encoding name/value pairs4as multipart/form-data suitable for a HTTP POST or PUT request.56multipart/form-data is the standard way to upload files over HTTP"""78__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',9 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',10 'multipart_encode']1112try:13 import uuid14 def gen_boundary():15 """Returns a random string to use as the boundary for a message"""16 return uuid.uuid4().hex17except ImportError:18 import random, sha19 def gen_boundary():20 """Returns a random string to use as the boundary for a message"""21 bits = random.getrandbits(160)22 return sha.new(str(bits)).hexdigest()2324import urllib, re, os, mimetypes25try:26 from email.header import Header27except ImportError:28 # Python 2.429 from email.Header import Header3031def encode_and_quote(data):32 """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))33 otherwise return urllib.quote_plus(data)"""34 if data is None:35 return None3637 if isinstance(data, unicode):38 data = data.encode("utf-8")39 return urllib.quote_plus(data)4041def _strify(s):42 """If s is a unicode string, encode it to UTF-8 and return the results,43 otherwise return str(s), or None if s is None"""44 if s is None:45 return None46 if isinstance(s, unicode):47 return s.encode("utf-8")48 return str(s)4950class MultipartParam(object):51 """Represents a single parameter in a multipart/form-data request5253 ``name`` is the name of this parameter.5455 If ``value`` is set, it must be a string or unicode object to use as the56 data for this parameter.5758 If ``filename`` is set, it is what to say that this parameter's filename59 is. Note that this does not have to be the actual filename any local file.6061 If ``filetype`` is set, it is used as the Content-Type for this parameter.62 If unset it defaults to "text/plain; charset=utf8"6364 If ``filesize`` is set, it specifies the length of the file ``fileobj``6566 If ``fileobj`` is set, it must be a file-like object that supports67 .read().6869 Both ``value`` and ``fileobj`` must not be set, doing so will70 raise a ValueError assertion.7172 If ``fileobj`` is set, and ``filesize`` is not specified, then73 the file's size will be determined first by stat'ing ``fileobj``'s74 file descriptor, and if that fails, by seeking to the end of the file,75 recording the current position as the size, and then by seeking back to the76 beginning of the file.7778 ``cb`` is a callable which will be called from iter_encode with (self,79 current, total), representing the current parameter, current amount80 transferred, and the total size.81 """82 def __init__(self, name, value=None, filename=None, filetype=None,83 filesize=None, fileobj=None, cb=None):84 self.name = Header(name).encode()85 self.value = _strify(value)86 if filename is None:87 self.filename = None88 else:89 if isinstance(filename, unicode):90 # Encode with XML entities91 self.filename = filename.encode("ascii", "xmlcharrefreplace")92 else:93 self.filename = str(filename)94 self.filename = self.filename.encode("string_escape").\95 replace('"', '\\"')96 self.filetype = _strify(filetype)9798 self.filesize = filesize99 self.fileobj = fileobj100 self.cb = cb101102 if self.value is not None and self.fileobj is not None:103 raise ValueError("Only one of value or fileobj may be specified")104105 if fileobj is not None and filesize is None:106 # Try and determine the file size107 try:108 self.filesize = os.fstat(fileobj.fileno()).st_size109 except (OSError, AttributeError):110 try:111 fileobj.seek(0, 2)112 self.filesize = fileobj.tell()113 fileobj.seek(0)114 except:115 raise ValueError("Could not determine filesize")116117 def __cmp__(self, other):118 attrs = ['name', 'value', 'filename', 'filetype', 'filesize', 'fileobj']119 myattrs = [getattr(self, a) for a in attrs]120 oattrs = [getattr(other, a) for a in attrs]121 return cmp(myattrs, oattrs)122123 def reset(self):124 if self.fileobj is not None:125 self.fileobj.seek(0)126 elif self.value is None:127 raise ValueError("Don't know how to reset this parameter")128129 @classmethod130 def from_file(cls, paramname, filename):131 """Returns a new MultipartParam object constructed from the local132 file at ``filename``.133134 ``filesize`` is determined by os.path.getsize(``filename``)135136 ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]137138 ``filename`` is set to os.path.basename(``filename``)139 """140141 return cls(paramname, filename=os.path.basename(filename),142 filetype=mimetypes.guess_type(filename)[0],143 filesize=os.path.getsize(filename),144 fileobj=open(filename, "rb"))145146 @classmethod147 def from_params(cls, params):148 """Returns a list of MultipartParam objects from a sequence of149 name, value pairs, MultipartParam instances,150 or from a mapping of names to values151152 The values may be strings or file objects, or MultipartParam objects.153 MultipartParam object names must match the given names in the154 name,value pairs or mapping, if applicable."""155 if hasattr(params, 'items'):156 params = params.items()157158 retval = []159 for item in params:160 if isinstance(item, cls):161 retval.append(item)162 continue163 name, value = item164 if isinstance(value, cls):165 assert value.name == name166 retval.append(value)167 continue168 if hasattr(value, 'read'):169 # Looks like a file object170 filename = getattr(value, 'name', None)171 if filename is not None:172 filetype = mimetypes.guess_type(filename)[0]173 else:174 filetype = None175176 retval.append(cls(name=name, filename=filename,177 filetype=filetype, fileobj=value))178 else:179 retval.append(cls(name, value))180 return retval181182 def encode_hdr(self, boundary):183 """Returns the header of the encoding of this parameter"""184 boundary = encode_and_quote(boundary)185186 headers = ["--%s" % boundary]187188 if self.filename:189 disposition = 'form-data; name="%s"; filename="%s"' % (self.name,190 self.filename)191 else:192 disposition = 'form-data; name="%s"' % self.name193194 headers.append("Content-Disposition: %s" % disposition)195196 if self.filetype:197 filetype = self.filetype198 else:199 filetype = "text/plain; charset=utf-8"200201 headers.append("Content-Type: %s" % filetype)202203 headers.append("")204 headers.append("")205206 return "\r\n".join(headers)207208 def encode(self, boundary):209 """Returns the string encoding of this parameter"""210 if self.value is None:211 value = self.fileobj.read()212 else:213 value = self.value214215 if re.search("^--%s$" % re.escape(boundary), value, re.M):216 raise ValueError("boundary found in encoded string")217218 return "%s%s\r\n" % (self.encode_hdr(boundary), value)219220 def iter_encode(self, boundary, blocksize=4096):221 """Yields the encoding of this parameter222 If self.fileobj is set, then blocks of ``blocksize`` bytes are read and223 yielded."""224 total = self.get_size(boundary)225 current = 0226 if self.value is not None:227 block = self.encode(boundary)228 current += len(block)229 yield block230 if self.cb:231 self.cb(self, current, total)232 else:233 block = self.encode_hdr(boundary)234 current += len(block)235 yield block236 if self.cb:237 self.cb(self, current, total)238 last_block = ""239 encoded_boundary = "--%s" % encode_and_quote(boundary)240 boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),241 re.M)242 while True:243 block = self.fileobj.read(blocksize)244 if not block:245 current += 2246 yield "\r\n"247 if self.cb:248 self.cb(self, current, total)249 break250 last_block += block251 if boundary_exp.search(last_block):252 raise ValueError("boundary found in file data")253 last_block = last_block[-len(encoded_boundary)-2:]254 current += len(block)255 yield block256 if self.cb:257 self.cb(self, current, total)258259 def get_size(self, boundary):260 """Returns the size in bytes that this param will be when encoded261 with the given boundary."""262 if self.filesize is not None:263 valuesize = self.filesize264 else:265 valuesize = len(self.value)266267 return len(self.encode_hdr(boundary)) + 2 + valuesize268269def encode_string(boundary, name, value):270 """Returns ``name`` and ``value`` encoded as a multipart/form-data271 variable. ``boundary`` is the boundary string used throughout272 a single request to separate variables."""273274 return MultipartParam(name, value).encode(boundary)275276def encode_file_header(boundary, paramname, filesize, filename=None,277 filetype=None):278 """Returns the leading data for a multipart/form-data field that contains279 file data.280281 ``boundary`` is the boundary string used throughout a single request to282 separate variables.283284 ``paramname`` is the name of the variable in this request.285286 ``filesize`` is the size of the file data.287288 ``filename`` if specified is the filename to give to this field. This289 field is only useful to the server for determining the original filename.290291 ``filetype`` if specified is the MIME type of this file.292293 The actual file data should be sent after this header has been sent.294 """295296 return MultipartParam(paramname, filesize=filesize, filename=filename,297 filetype=filetype).encode_hdr(boundary)298299def get_body_size(params, boundary):300 """Returns the number of bytes that the multipart/form-data encoding301 of ``params`` will be."""302 size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))303 return size + len(boundary) + 6304305def get_headers(params, boundary):306 """Returns a dictionary with Content-Type and Content-Length headers307 for the multipart/form-data encoding of ``params``."""308 headers = {}309 boundary = urllib.quote_plus(boundary)310 headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary311 headers['Content-Length'] = str(get_body_size(params, boundary))312 return headers313314class multipart_yielder:315 def __init__(self, params, boundary, cb):316 self.params = params317 self.boundary = boundary318 self.cb = cb319320 self.i = 0321 self.p = None322 self.param_iter = None323 self.current = 0324 self.total = get_body_size(params, boundary)325326 def __iter__(self):327 return self328329 def next(self):330 """generator function to yield multipart/form-data representation331 of parameters"""332 if self.param_iter is not None:333 try:334 block = self.param_iter.next()335 self.current += len(block)336 if self.cb:337 self.cb(self.p, self.current, self.total)338 return block339 except StopIteration:340 self.p = None341 self.param_iter = None342343 if self.i is None:344 raise StopIteration345 elif self.i >= len(self.params):346 self.param_iter = None347 self.p = None348 self.i = None349 block = "--%s--\r\n" % self.boundary350 self.current += len(block)351 if self.cb:352 self.cb(self.p, self.current, self.total)353 return block354355 self.p = self.params[self.i]356 self.param_iter = self.p.iter_encode(self.boundary)357 self.i += 1358 return self.next()359360 def reset(self):361 self.i = 0362 self.current = 0363 for param in self.params:364 param.reset()365366def multipart_encode(params, boundary=None, cb=None):367 """Encode ``params`` as multipart/form-data.368369 ``params`` should be a sequence of (name, value) pairs or MultipartParam370 objects, or a mapping of names to values.371 Values are either strings parameter values, or file-like objects to use as372 the parameter value. The file-like objects must support .read() and either373 .fileno() or both .seek() and .tell().374375 If ``boundary`` is set, then it as used as the MIME boundary. Otherwise376 a randomly generated boundary will be used. In either case, if the377 boundary string appears in the parameter values a ValueError will be378 raised.379380 If ``cb`` is set, it should be a callback which will get called as blocks381 of data are encoded. It will be called with (param, current, total),382 indicating the current parameter being encoded, the current amount encoded,383 and the total amount to encode.384385 Returns a tuple of `datagen`, `headers`, where `datagen` is a386 generator that will yield blocks of data that make up the encoded387 parameters, and `headers` is a dictionary with the assoicated388 Content-Type and Content-Length headers.389390 Examples:391392 >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )393 >>> s = "".join(datagen)394 >>> assert "value2" in s and "value1" in s395396 >>> p = MultipartParam("key", "value2")397 >>> datagen, headers = multipart_encode( [("key", "value1"), p] )398 >>> s = "".join(datagen)399 >>> assert "value2" in s and "value1" in s400401 >>> datagen, headers = multipart_encode( {"key": "value1"} )402 >>> s = "".join(datagen)403 >>> assert "value2" not in s and "value1" in s404405 """406 if boundary is None:407 boundary = gen_boundary()408 else:409 boundary = urllib.quote_plus(boundary)410411 headers = get_headers(params, boundary)412 params = MultipartParam.from_params(params)413414 return multipart_yielder(params, boundary, cb), headers
deleted:requests/packages/poster/streaminghttp.py-199 removed
1"""Streaming HTTP uploads module.23This module extends the standard httplib and urllib2 objects so that4iterable objects can be used in the body of HTTP requests.56In most cases all one should have to do is call :func:`register_openers()`7to register the new streaming http handlers which will take priority over8the default handlers, and then you can use iterable objects in the body9of HTTP requests.1011**N.B.** You must specify a Content-Length header if using an iterable object12since there is no way to determine in advance the total size that will be13yielded, and there is no way to reset an interator.1415Example usage:1617>>> from StringIO import StringIO18>>> import urllib2, poster.streaminghttp1920>>> opener = poster.streaminghttp.register_openers()2122>>> s = "Test file data"23>>> f = StringIO(s)2425>>> req = urllib2.Request("http://localhost:5000", f,26... {'Content-Length': str(len(s))})27"""2829import httplib, urllib2, socket30from httplib import NotConnected3132__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',33 'StreamingHTTPHandler', 'register_openers']3435if hasattr(httplib, 'HTTPS'):36 __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])3738class _StreamingHTTPMixin:39 """Mixin class for HTTP and HTTPS connections that implements a streaming40 send method."""41 def send(self, value):42 """Send ``value`` to the server.4344 ``value`` can be a string object, a file-like object that supports45 a .read() method, or an iterable object that supports a .next()46 method.47 """48 # Based on python 2.6's httplib.HTTPConnection.send()49 if self.sock is None:50 if self.auto_open:51 self.connect()52 else:53 raise NotConnected()5455 # send the data to the server. if we get a broken pipe, then close56 # the socket. we want to reconnect when somebody tries to send again.57 #58 # NOTE: we DO propagate the error, though, because we cannot simply59 # ignore the error... the caller will know if they can retry.60 if self.debuglevel > 0:61 print "send:", repr(value)62 try:63 blocksize = 819264 if hasattr(value, 'read') :65 if hasattr(value, 'seek'):66 value.seek(0)67 if self.debuglevel > 0:68 print "sendIng a read()able"69 data = value.read(blocksize)70 while data:71 self.sock.sendall(data)72 data = value.read(blocksize)73 elif hasattr(value, 'next'):74 if hasattr(value, 'reset'):75 value.reset()76 if self.debuglevel > 0:77 print "sendIng an iterable"78 for data in value:79 self.sock.sendall(data)80 else:81 self.sock.sendall(value)82 except socket.error, v:83 if v[0] == 32: # Broken pipe84 self.close()85 raise8687class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):88 """Subclass of `httplib.HTTPConnection` that overrides the `send()` method89 to support iterable body objects"""9091class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):92 """Subclass of `urllib2.HTTPRedirectHandler` that overrides the93 `redirect_request` method to properly handle redirected POST requests9495 This class is required because python 2.5's HTTPRedirectHandler does96 not remove the Content-Type or Content-Length headers when requesting97 the new resource, but the body of the original request is not preserved.98 """99100 handler_order = urllib2.HTTPRedirectHandler.handler_order - 1101102 # From python2.6 urllib2's HTTPRedirectHandler103 def redirect_request(self, req, fp, code, msg, headers, newurl):104 """Return a Request or None in response to a redirect.105106 This is called by the http_error_30x methods when a107 redirection response is received. If a redirection should108 take place, return a new Request to allow http_error_30x to109 perform the redirect. Otherwise, raise HTTPError if no-one110 else should try to handle this url. Return None if you can't111 but another Handler might.112 """113 m = req.get_method()114 if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")115 or code in (301, 302, 303) and m == "POST"):116 # Strictly (according to RFC 2616), 301 or 302 in response117 # to a POST MUST NOT cause a redirection without confirmation118 # from the user (of urllib2, in this case). In practice,119 # essentially all clients do redirect in this case, so we120 # do the same.121 # be conciliant with URIs containing a space122 newurl = newurl.replace(' ', '%20')123 newheaders = dict((k, v) for k, v in req.headers.items()124 if k.lower() not in (125 "content-length", "content-type")126 )127 return urllib2.Request(newurl,128 headers=newheaders,129 origin_req_host=req.get_origin_req_host(),130 unverifiable=True)131 else:132 raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)133134class StreamingHTTPHandler(urllib2.HTTPHandler):135 """Subclass of `urllib2.HTTPHandler` that uses136 StreamingHTTPConnection as its http connection class."""137138 handler_order = urllib2.HTTPHandler.handler_order - 1139140 def http_open(self, req):141 """Open a StreamingHTTPConnection for the given request"""142 return self.do_open(StreamingHTTPConnection, req)143144 def http_request(self, req):145 """Handle a HTTP request. Make sure that Content-Length is specified146 if we're using an interable value"""147 # Make sure that if we're using an iterable object as the request148 # body, that we've also specified Content-Length149 if req.has_data():150 data = req.get_data()151 if hasattr(data, 'read') or hasattr(data, 'next'):152 if not req.has_header('Content-length'):153 raise ValueError(154 "No Content-Length specified for iterable body")155 return urllib2.HTTPHandler.do_request_(self, req)156157if hasattr(httplib, 'HTTPS'):158 class StreamingHTTPSConnection(_StreamingHTTPMixin,159 httplib.HTTPSConnection):160 """Subclass of `httplib.HTTSConnection` that overrides the `send()`161 method to support iterable body objects"""162163 class StreamingHTTPSHandler(urllib2.HTTPSHandler):164 """Subclass of `urllib2.HTTPSHandler` that uses165 StreamingHTTPSConnection as its http connection class."""166167 handler_order = urllib2.HTTPSHandler.handler_order - 1168169 def https_open(self, req):170 return self.do_open(StreamingHTTPSConnection, req)171172 def https_request(self, req):173 # Make sure that if we're using an iterable object as the request174 # body, that we've also specified Content-Length175 if req.has_data():176 data = req.get_data()177 if hasattr(data, 'read') or hasattr(data, 'next'):178 if not req.has_header('Content-length'):179 raise ValueError(180 "No Content-Length specified for iterable body")181 return urllib2.HTTPSHandler.do_request_(self, req)182183184def get_handlers():185 handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186 if hasattr(httplib, "HTTPS"):187 handlers.append(StreamingHTTPSHandler)188 return handlers189 190def register_openers():191 """Register the streaming http handlers in the global urllib2 default192 opener object.193194 Returns the created OpenerDirector object."""195 opener = urllib2.build_opener(*get_handlers())196197 urllib2.install_opener(opener)198199 return opener
added:requests/packages/urllib3/contrib/__init__.py
added:requests/packages/urllib3/contrib/ntlmpool.py+117 added
1# urllib3/contrib/ntlmpool.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.php67"""8NTLM authenticating pool, contributed by erikcederstran910Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011"""1213import httplib14from logging import getLogger15from ntlm import ntlm1617from urllib3 import HTTPSConnectionPool181920log = getLogger(__name__)212223class NTLMConnectionPool(HTTPSConnectionPool):24 """25 Implements an NTLM authentication version of an urllib3 connection pool26 """2728 scheme = 'https'2930 def __init__(self, user, pw, authurl, *args, **kwargs):31 """32 authurl is a random URL on the server that is protected by NTLM.33 user is the Windows user, probably in the DOMAIN\username format.34 pw is the password for the user.35 """36 super(NTLMConnectionPool, self).__init__(*args, **kwargs)37 self.authurl = authurl38 self.rawuser = user39 user_parts = user.split('\\', 1)40 self.domain = user_parts[0].upper()41 self.user = user_parts[1]42 self.pw = pw4344 def _new_conn(self):45 # Performs the NTLM handshake that secures the connection. The socket46 # must be kept open while requests are performed.47 self.num_connections += 148 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' %49 (self.num_connections, self.host, self.authurl))5051 headers = {}52 headers['Connection'] = 'Keep-Alive'53 req_header = 'Authorization'54 resp_header = 'www-authenticate'5556 conn = httplib.HTTPSConnection(host=self.host, port=self.port)5758 # Send negotiation message59 headers[req_header] = (60 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))61 log.debug('Request headers: %s' % headers)62 conn.request('GET', self.authurl, None, headers)63 res = conn.getresponse()64 reshdr = dict(res.getheaders())65 log.debug('Response status: %s %s' % (res.status, res.reason))66 log.debug('Response headers: %s' % reshdr)67 log.debug('Response data: %s [...]' % res.read(100))6869 # Remove the reference to the socket, so that it can not be closed by70 # the response object (we want to keep the socket open)71 res.fp = None7273 # Server should respond with a challenge message74 auth_header_values = reshdr[resp_header].split(', ')75 auth_header_value = None76 for s in auth_header_values:77 if s[:5] == 'NTLM ':78 auth_header_value = s[5:]79 if auth_header_value is None:80 raise Exception('Unexpected %s response header: %s' %81 (resp_header, reshdr[resp_header]))8283 # Send authentication message84 ServerChallenge, NegotiateFlags = \85 ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)86 auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,87 self.user,88 self.domain,89 self.pw,90 NegotiateFlags)91 headers[req_header] = 'NTLM %s' % auth_msg92 log.debug('Request headers: %s' % headers)93 conn.request('GET', self.authurl, None, headers)94 res = conn.getresponse()95 log.debug('Response status: %s %s' % (res.status, res.reason))96 log.debug('Response headers: %s' % dict(res.getheaders()))97 log.debug('Response data: %s [...]' % res.read()[:100])98 if res.status != 200:99 if res.status == 401:100 raise Exception('Server rejected request: wrong '101 'username or password')102 raise Exception('Wrong server response: %s %s' %103 (res.status, res.reason))104105 res.fp = None106 log.debug('Connection established')107 return conn108109 def urlopen(self, method, url, body=None, headers=None, retries=3,110 redirect=True, assert_same_host=True):111 if headers is None:112 headers = {}113 headers['Connection'] = 'Keep-Alive'114 return super(NTLMConnectionPool, self).urlopen(method, url, body,115 headers, retries,116 redirect,117 assert_same_host)
added:requests/packages/urllib3/__init__.py+48 added
1# urllib3/__init__.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.php67"""8urllib3 - Thread-safe connection pooling and re-using.9"""1011__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12__license__ = 'MIT'13__version__ = '1.0.2'141516from .connectionpool import (17 HTTPConnectionPool,18 HTTPSConnectionPool,19 connection_from_url,20 get_host,21 make_headers)222324from .exceptions import (25 HTTPError,26 MaxRetryError,27 SSLError,28 TimeoutError)2930from .poolmanager import PoolManager, ProxyManager, proxy_from_url31from .response import HTTPResponse32from .filepost import encode_multipart_formdata333435# Set default logging handler to avoid "No handler found" warnings.36import logging37try:38 from logging import NullHandler39except ImportError:40 class NullHandler(logging.Handler):41 def emit(self, record):42 pass4344logging.getLogger(__name__).addHandler(NullHandler())4546# ... Clean up.47del logging48del NullHandler
added:requests/packages/urllib3/_collections.py+131 added
1# urllib3/_collections.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.php67from collections import deque89from threading import RLock1011__all__ = ['RecentlyUsedContainer']121314class AccessEntry(object):15 __slots__ = ('key', 'is_valid')1617 def __init__(self, key, is_valid=True):18 self.key = key19 self.is_valid = is_valid202122class RecentlyUsedContainer(dict):23 """24 Provides a dict-like that maintains up to ``maxsize`` keys while throwing25 away the least-recently-used keys beyond ``maxsize``.26 """2728 # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we29 # will attempt to cleanup the invalidated entries in the access_log30 # datastructure during the next 'get' operation.31 CLEANUP_FACTOR = 103233 def __init__(self, maxsize=10):34 self._maxsize = maxsize3536 self._container = {}3738 # We use a deque to to store our keys ordered by the last access.39 self.access_log = deque()40 self.access_log_lock = RLock()4142 # We look up the access log entry by the key to invalidate it so we can43 # insert a new authorative entry at the head without having to dig and44 # find the old entry for removal immediately.45 self.access_lookup = {}4647 # Trigger a heap cleanup when we get past this size48 self.access_log_limit = maxsize * self.CLEANUP_FACTOR4950 def _invalidate_entry(self, key):51 "If exists: Invalidate old entry and return it."52 old_entry = self.access_lookup.get(key)53 if old_entry:54 old_entry.is_valid = False5556 return old_entry5758 def _push_entry(self, key):59 "Push entry onto our access log, invalidate the old entry if exists."60 self._invalidate_entry(key)6162 new_entry = AccessEntry(key)63 self.access_lookup[key] = new_entry6465 self.access_log_lock.acquire()66 self.access_log.appendleft(new_entry)67 self.access_log_lock.release()6869 def _prune_entries(self, num):70 "Pop entries from our access log until we popped ``num`` valid ones."71 while num > 0:72 self.access_log_lock.acquire()73 p = self.access_log.pop()74 self.access_log_lock.release()7576 if not p.is_valid:77 continue # Invalidated entry, skip7879 dict.pop(self, p.key, None)80 self.access_lookup.pop(p.key, None)81 num -= 18283 def _prune_invalidated_entries(self):84 "Rebuild our access_log without the invalidated entries."85 self.access_log_lock.acquire()86 self.access_log = deque(e for e in self.access_log if e.is_valid)87 self.access_log_lock.release()8889 def _get_ordered_access_keys(self):90 "Return ordered access keys for inspection. Used for testing."91 self.access_log_lock.acquire()92 r = [e.key for e in self.access_log if e.is_valid]93 self.access_log_lock.release()9495 return r9697 def __getitem__(self, key):98 item = dict.get(self, key)99100 if not item:101 raise KeyError(key)102103 # Insert new entry with new high priority, also implicitly invalidates104 # the old entry.105 self._push_entry(key)106107 if len(self.access_log) > self.access_log_limit:108 # Heap is getting too big, try to clean up any tailing invalidated109 # entries.110 self._prune_invalidated_entries()111112 return item113114 def __setitem__(self, key, item):115 # Add item to our container and access log116 dict.__setitem__(self, key, item)117 self._push_entry(key)118119 # Discard invalid and excess entries120 self._prune_entries(len(self) - self._maxsize)121122 def __delitem__(self, key):123 self._invalidate_entry(key)124 self.access_lookup.pop(key, None)125 dict.__delitem__(self, key)126127 def get(self, key, default=None):128 try:129 return self[key]130 except KeyError:131 return default
added:requests/packages/urllib3/connectionpool.py+525 added
1# urllib3/connectionpool.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.php67import logging8import socket91011from httplib import HTTPConnection, HTTPSConnection, HTTPException12from Queue import Queue, Empty, Full13from select import select14from socket import error as SocketError, timeout as SocketTimeout151617try:18 import ssl19 BaseSSLError = ssl.SSLError20except ImportError:21 ssl = None22 BaseSSLError = None232425from .request import RequestMethods26from .response import HTTPResponse27from .exceptions import (28 SSLError,29 MaxRetryError,30 TimeoutError,31 HostChangedError,32 EmptyPoolError,33)343536log = logging.getLogger(__name__)3738_Default = object()394041## Connection objects (extension of httplib)4243class VerifiedHTTPSConnection(HTTPSConnection):44 """45 Based on httplib.HTTPSConnection but wraps the socket with46 SSL certification.47 """48 cert_reqs = None49 ca_certs = None5051 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,55 'CERT_OPTIONAL': ssl.CERT_OPTIONAL,56 'CERT_REQUIRED': ssl.CERT_REQUIRED57 }5859 self.key_file = key_file60 self.cert_file = cert_file61 self.cert_reqs = ssl_req_scheme.get(cert_reqs) or ssl.CERT_NONE62 self.ca_certs = ca_certs6364 def connect(self):65 # Add certificate verification66 sock = socket.create_connection((self.host, self.port), self.timeout)6768 # Wrap socket using verification with the root certs in69 # trusted_root_certs70 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,71 cert_reqs=self.cert_reqs,72 ca_certs=self.ca_certs)737475## Pool objects7677class ConnectionPool(object):78 """79 Base class for all connection pools, such as80 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.81 """82 pass838485class HTTPConnectionPool(ConnectionPool, RequestMethods):86 """87 Thread-safe connection pool for one host.8889 :param host:90 Host used for this HTTP Connection (e.g. "localhost"), passed into91 :class:`httplib.HTTPConnection`.9293 :param port:94 Port used for this HTTP Connection (None is equivalent to 80), passed95 into :class:`httplib.HTTPConnection`.9697 :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 :class:`httplib.HTTPConnection`.101102 :param timeout:103 Socket timeout for each individual connection, can be a float. None104 disables timeout.105106 :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.111112 :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.118119 :param headers:120 Headers to include with all requests, unless other headers are given121 explicitly.122 """123124 scheme = 'http'125126 def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,127 block=False, headers=None):128 self.host = host129 self.port = port130 self.strict = strict131 self.timeout = timeout132 self.pool = Queue(maxsize)133 self.block = block134 self.headers = headers or {}135136 # Fill the queue up so that doing get() on it will block properly137 for _ in xrange(maxsize):138 self.pool.put(None)139140 # These are mostly for testing and debugging purposes.141 self.num_connections = 0142 self.num_requests = 0143144 def _new_conn(self):145 """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))151 return HTTPConnection(host=self.host, port=self.port)152153 def _get_conn(self, timeout=None):154 """155 Get a connection. Will return a pooled connection if one is available.156157 If no connections are available and :prop:`.block` is ``False``, then a158 fresh connection is returned.159160 :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)168169 # If this is a persistent connection, check if it got disconnected170 if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:171 # Either data is buffered (bad), or the connection is dropped.172 log.info("Resetting dropped connection: %s" % self.host)173 conn.close()174175 except Empty:176 if self.block:177 raise EmptyPoolError("Pool reached maximum size and no more "178 "connections are allowed.")179 pass # Oh well, we'll create a new connection then180181 return conn or self._new_conn()182183 def _put_conn(self, conn):184 """185 Put a connection back into the pool.186187 :param conn:188 Connection object for the current host and port as returned by189 :meth:`._new_conn` or :meth:`._get_conn`.190191 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 """195 try:196 self.pool.put(conn, block=False)197 except Full:198 # This should never happen if self.block == True199 log.warning("HttpConnectionPool is full, discarding connection: %s"200 % self.host)201202 def _make_request(self, conn, method, url, timeout=_Default,203 **httplib_request_kw):204 """205 Perform a request on a given httplib connection object taken from our206 pool.207 """208 self.num_requests += 1209210 if timeout is _Default:211 timeout = self.timeout212213 conn.request(method, url, **httplib_request_kw)214 conn.sock.settimeout(timeout)215 httplib_response = conn.getresponse()216217 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))221222 return httplib_response223224225 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))233234 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 """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.241242 .. note::243244 More commonly, it's appropriate to use a convenience method provided245 by :class:`.RequestMethods`, such as :meth:`.request`.246247 :param method:248 HTTP request method (such as GET, POST, PUT, etc.)249250 :param body:251 Data to send in the request body (useful for creating252 POST requests, see HTTPConnectionPool.post_url for253 more convenience).254255 :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.259260 :param retries:261 Number of retries to allow before raising a MaxRetryError exception.262263 :param redirect:264 Automatically handle redirects (status codes 301, 302, 303, 307),265 each redirect counts as a retry.266267 :param assert_same_host:268 If ``True``, will make sure that the host of the pool requests is269 consistent else will raise HostChangedError. When False, you can270 use the pool on an HTTP proxy and request foreign hosts.271272 :param timeout:273 If specified, overrides the default timeout for this one request.274275 :param pool_timeout:276 If set and the pool is set to block=True, then this method will277 block for ``pool_timeout`` seconds and raise EmptyPoolError if no278 connection is available within the time period.279280 :param release_conn:281 If False, then the urlopen call will not release the connection282 back into the pool once a response is received. This is useful if283 you're not preloading the response's content immediately. You will284 need to call ``r.release_conn()`` on the response ``r`` to return285 the connection back into the pool. If None, it takes the value of286 ``response_kw.get('preload_content', True)``.287288 :param \**response_kw:289 Additional parameters are passed to290 :meth:`urllib3.response.HTTPResponse.from_httplib`291 """292 if headers is None:293 headers = self.headers294295 if retries < 0:296 raise MaxRetryError("Max retries exceeded for url: %s" % url)297298 if release_conn is None:299 release_conn = response_kw.get('preload_content', True)300301 # Check host302 if assert_same_host and not self.is_same_host(url):303 host = "%s://%s" % (self.scheme, self.host)304 if self.port:305 host = "%s:%d" % (host, self.port)306307 raise HostChangedError("Connection pool with host '%s' tried to "308 "open a foreign host: %s" % (host, url))309310 conn = None311312 try:313 # Request a connection from the queue314 # (Could raise SocketError: Bad file descriptor)315 conn = self._get_conn(timeout=pool_timeout)316317 # Make the request on the httplib connection object318 httplib_response = self._make_request(conn, method, url,319 timeout=timeout,320 body=body, headers=headers)321322 # If we're going to release the connection in ``finally:``, then323 # the request doesn't need to know about the connection. Otherwise324 # it will also try to release it and we'll have a double-release325 # mess.326 response_conn = not release_conn and conn327328 # Import httplib's response into our own wrapper object329 response = HTTPResponse.from_httplib(httplib_response,330 pool=self,331 connection=response_conn,332 **response_kw)333334 # else:335 # The connection will be put back into the pool when336 # ``response.release_conn()`` is called (implicitly by337 # ``response.read()``)338339 except (SocketTimeout, Empty), e:340 # Timed out either by socket or queue341 raise TimeoutError("Request timed out after %f seconds" %342 self.timeout)343344 except (BaseSSLError), e:345 # SSL certificate error346 raise SSLError(e)347348 except (HTTPException, SocketError), e:349 # Connection broken, discard. It will be replaced next _get_conn().350 conn = None351352 finally:353 if conn and release_conn:354 # Put the connection back to be reused355 self._put_conn(conn)356357 if not conn:358 log.warn("Retrying (%d attempts remain) after connection "359 "broken by '%r': %s" % (retries, e, url))360 return self.urlopen(method, url, body, headers, retries - 1,361 redirect, assert_same_host) # Try again362363 # Handle redirection364 if (redirect and365 response.status in [301, 302, 303, 307] and366 'location' in response.headers): # Redirect, retry367 log.info("Redirecting %s -> %s" %368 (url, response.headers.get('location')))369 return self.urlopen(method, response.headers.get('location'), body,370 headers, retries - 1, redirect,371 assert_same_host)372373 return response374375376class HTTPSConnectionPool(HTTPConnectionPool):377 """378 Same as :class:`.HTTPConnectionPool`, but HTTPS.379380 When Python is compiled with the :mod:`ssl` module, then381 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,382 instead of :class:httplib.HTTPSConnection`.383384 The ``key_file``, ``cert_file``, ``cert_reqs``, and ``ca_certs`` parameters385 are only used if :mod:`ssl` is available and are fed into386 :meth:`ssl.wrap_socket` to upgrade the connection socket into an SSL socket.387 """388389 scheme = 'https'390391 def __init__(self, host, port=None,392 strict=False, timeout=None, maxsize=1,393 block=False, headers=None,394 key_file=None, cert_file=None,395 cert_reqs='CERT_NONE', ca_certs=None):396397 super(HTTPSConnectionPool, self).__init__(host, port,398 strict, timeout, maxsize,399 block, headers)400 self.key_file = key_file401 self.cert_file = cert_file402 self.cert_reqs = cert_reqs403 self.ca_certs = ca_certs404405 def _new_conn(self):406 """407 Return a fresh :class:`httplib.HTTPSConnection`.408 """409 self.num_connections += 1410 log.info("Starting new HTTPS connection (%d): %s"411 % (self.num_connections, self.host))412413 if not ssl:414 return HTTPSConnection(host=self.host, port=self.port)415416 connection = VerifiedHTTPSConnection(host=self.host, port=self.port)417 connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,418 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)419 return connection420421422## Helpers423424def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,425 basic_auth=None):426 """427 Shortcuts for generating request headers.428429 :param keep_alive:430 If ``True``, adds 'connection: keep-alive' header.431432 :param accept_encoding:433 Can be a boolean, list, or string.434 ``True`` translates to 'gzip,deflate'.435 List will get joined by comma.436 String will be used as provided.437438 :param user_agent:439 String representing the user-agent you want, such as440 "python-urllib3/0.6"441442 :param basic_auth:443 Colon-separated username:password string for 'authorization: basic ...'444 auth header.445446 Example: ::447448 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")449 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}450 >>> make_headers(accept_encoding=True)451 {'accept-encoding': 'gzip,deflate'}452 """453 headers = {}454 if accept_encoding:455 if isinstance(accept_encoding, str):456 pass457 elif isinstance(accept_encoding, list):458 accept_encoding = ','.join(accept_encoding)459 else:460 accept_encoding = 'gzip,deflate'461 headers['accept-encoding'] = accept_encoding462463 if user_agent:464 headers['user-agent'] = user_agent465466 if keep_alive:467 headers['connection'] = 'keep-alive'468469 if basic_auth:470 headers['authorization'] = 'Basic ' + \471 basic_auth.encode('base64').strip()472473 return headers474475476def get_host(url):477 """478 Given a url, return its scheme, host and port (None if it's not there).479480 For example: ::481482 >>> get_host('http://google.com/mail/')483 ('http', 'google.com', None)484 >>> get_host('google.com:80')485 ('http', 'google.com', 80)486 """487 # This code is actually similar to urlparse.urlsplit, but much488 # simplified for our needs.489 port = None490 scheme = 'http'491 if '//' in url:492 scheme, url = url.split('://', 1)493 if '/' in url:494 url, _path = url.split('/', 1)495 if ':' in url:496 url, port = url.split(':', 1)497 port = int(port)498 return scheme, url, port499500501def connection_from_url(url, **kw):502 """503 Given a url, return an :class:`.ConnectionPool` instance of its host.504505 This is a shortcut for not having to parse out the scheme, host, and port506 of the url before creating an :class:`.ConnectionPool` instance.507508 :param url:509 Absolute URL string that must include the scheme. Port is optional.510511 :param \**kw:512 Passes additional parameters to the constructor of the appropriate513 :class:`.ConnectionPool`. Useful for specifying things like514 timeout, maxsize, headers, etc.515516 Example: ::517518 >>> conn = connection_from_url('http://google.com/')519 >>> r = conn.request('GET', '/')520 """521 scheme, host, port = get_host(url)522 if scheme == 'https':523 return HTTPSConnectionPool(host, port=port, **kw)524 else:525 return HTTPConnectionPool(host, port=port, **kw)
added:requests/packages/urllib3/exceptions.py+35 added
1# urllib3/exceptions.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.php67## Exceptions89class HTTPError(Exception):10 "Base exception used by this module."11 pass121314class SSLError(Exception):15 "Raised when SSL certificate fails in an HTTPS connection."16 pass171819class MaxRetryError(HTTPError):20 "Raised when the maximum number of retries is exceeded."21 pass222324class TimeoutError(HTTPError):25 "Raised when a socket timeout occurs."26 pass272829class HostChangedError(HTTPError):30 "Raised when an existing pool gets a request for a foreign host."31 pass3233class EmptyPoolError(HTTPError):34 "Raised when a pool runs out of connections and no more are allowed."35 pass
added:requests/packages/urllib3/filepost.py+71 added
1# urllib3/filepost.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.php67import codecs8import mimetools9import mimetypes1011try:12 from cStringIO import StringIO13except ImportError:14 from StringIO import StringIO # pylint: disable-msg=W0404151617writer = codecs.lookup('utf-8')[3]181920def get_content_type(filename):21 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'222324def encode_multipart_formdata(fields, boundary=None):25 """26 Encode a dictionary of ``fields`` using the multipart/form-data mime format.2728 :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.3334 :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()4142 for fieldname, value in fields.iteritems():43 body.write('--%s\r\n' % (boundary))4445 if isinstance(value, tuple):46 filename, data = value47 writer(body).write('Content-Disposition: form-data; name="%s"; '48 'filename="%s"\r\n' % (fieldname, filename))49 body.write('Content-Type: %s\r\n\r\n' %50 (get_content_type(filename)))51 else:52 data = value53 writer(body).write('Content-Disposition: form-data; name="%s"\r\n'54 % (fieldname))55 body.write('Content-Type: text/plain\r\n\r\n')5657 if isinstance(data, int):58 data = str(data) # Backwards compatibility5960 if isinstance(data, unicode):61 writer(body).write(data)62 else:63 body.write(data)6465 body.write('\r\n')6667 body.write('--%s--\r\n' % (boundary))6869 content_type = 'multipart/form-data; boundary=%s' % boundary7071 return body.getvalue(), content_type
added:requests/packages/urllib3/poolmanager.py+128 added
1# urllib3/poolmanager.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.php67from ._collections import RecentlyUsedContainer8from .connectionpool import (9 HTTPConnectionPool, HTTPSConnectionPool,10 get_host, connection_from_url,11)121314__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']151617from .request import RequestMethods18from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool192021pool_classes_by_scheme = {22 'http': HTTPConnectionPool,23 'https': HTTPSConnectionPool,24}2526port_by_scheme = {27 'http': 80,28 'https': 443,29}303132class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.3637 :param num_pools:38 Number of connection pools to cache before discarding the least recently39 used pool.4041 :param \**connection_pool_kw:42 Additional parameters are used to create fresh43 :class:`urllib3.connectionpool.ConnectionPool` instances.4445 Example: ::4647 >>> 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 25354 """5556 # TODO: Make sure there are no memory leaks here.5758 def __init__(self, num_pools=10, **connection_pool_kw):59 self.connection_pool_kw = connection_pool_kw60 self.pools = RecentlyUsedContainer(num_pools)6162 def connection_from_host(self, host, port=80, scheme='http'):63 """64 Get a :class:`ConnectionPool` based on the host, port, and scheme.6566 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)7071 # 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:75 return pool7677 # Make a fresh ConnectionPool of the desired type78 pool_cls = pool_classes_by_scheme[scheme]79 pool = pool_cls(host, port, **self.connection_pool_kw)8081 self.pools[pool_key] = pool8283 return pool8485 def connection_from_url(self, url):86 """87 Similar to :func:`urllib3.connectionpool.connection_from_url` but88 doesn't pass any additional parameters to the89 :class:`urllib3.connectionpool.ConnectionPool` constructor.9091 Additional parameters are taken from the :class:`.PoolManager`92 constructor.93 """94 scheme, host, port = get_host(url)9596 port = port or port_by_scheme.get(scheme, 80)9798 return self.connection_from_host(host, port=port, scheme=scheme)99100 def urlopen(self, method, url, **kw):101 """102 Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.103104 ``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)109110111class ProxyManager(RequestMethods):112 """113 Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method114 will make requests to any url through the defined proxy.115 """116117 def __init__(self, proxy_pool):118 self.proxy_pool = proxy_pool119120 def urlopen(self, method, url, **kw):121 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."122 kw['assert_same_host'] = False123 return self.proxy_pool.urlopen(method, url, **kw)124125126def 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.php678from urllib import urlencode910from .filepost import encode_multipart_formdata111213__all__ = ['RequestMethods']141516class 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`.2122 Provides behavior for making common types of HTTP request methods and23 decides which type of request field encoding to use.2425 Specifically,2627 :meth:`.request_encode_url` is for sending requests whose fields are encoded28 in the URL (such as GET, HEAD, DELETE).2930 :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).3334 :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 """3839 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])4041 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])4243 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.")4849 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.5354 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()6162 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)7071 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)7980 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.8687 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.9293 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.9697 Supports an optional ``fields`` parameter of key/value strings AND98 key/filetuple. A filetuple is a (filename, data) tuple. For example: ::99100 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 }106107 When uploading a file, providing a filename (the first parameter of the108 tuple) is optional but recommended to best mimick behavior of browsers.109110 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')121122 headers = headers or {}123 headers.update({'Content-Type': content_type})124125 return self.urlopen(method, url, body=body, headers=headers,126 **urlopen_kw)127128 # Deprecated:129130 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)137138 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)
added:requests/packages/urllib3/response.py+181 added
1# urllib3/response.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.php67import gzip8import logging9import zlib101112try:13 from cStringIO import StringIO14except ImportError:15 from StringIO import StringIO # pylint: disable-msg=W0404161718from .exceptions import HTTPError192021log = logging.getLogger(__name__)222324def decode_gzip(data):25 gzipper = gzip.GzipFile(fileobj=StringIO(data))26 return gzipper.read()272829def decode_deflate(data):30 try:31 return zlib.decompress(data)32 except zlib.error:33 return zlib.decompress(data, -zlib.MAX_WBITS)343536class HTTPResponse(object):37 """38 HTTP Response container.3940 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is41 loaded and decoded on-demand when the ``data`` property is accessed.4243 Extra parameters for behaviour not present in httplib.HTTPResponse:4445 :param preload_content:46 If True, the response's body will be preloaded during construction.4748 :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.5253 :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 """5859 CONTENT_DECODERS = {60 'gzip': decode_gzip,61 'deflate': decode_deflate,62 }6364 def __init__(self, body='', headers=None, status=0, version=0, reason=None,65 strict=0, preload_content=True, decode_content=True,66 original_response=None, pool=None, connection=None):67 self.headers = headers or {}68 self.status = status69 self.version = version70 self.reason = reason71 self.strict = strict7273 self._decode_content = decode_content74 self._body = None75 self._fp = None76 self._original_response = original_response7778 self._pool = pool79 self._connection = connection8081 if hasattr(body, 'read'):82 self._fp = body8384 if preload_content:85 self._body = self.read(decode_content=decode_content)8687 def release_conn(self):88 if not self._pool or not self._connection:89 return9091 self._pool._put_conn(self._connection)92 self._connection = None9394 @property95 def data(self):96 # For backwords-compat with earlier urllib3 0.4 and earlier.97 if self._body:98 return self._body99100 if self._fp:101 return self.read(decode_content=self._decode_content,102 cache_content=True)103104 def read(self, amt=None, decode_content=True, cache_content=False):105 """106 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional107 parameters: ``decode_content`` and ``cache_content``.108109 :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.113114 :param decode_content:115 If True, will attempt to decode the body based on the116 'content-encoding' header. (Overridden if ``amt`` is set.)117118 :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`` is123 set.)124 """125 content_encoding = self.headers.get('content-encoding')126 decoder = self.CONTENT_DECODERS.get(content_encoding)127128 data = self._fp and self._fp.read(amt)129130 try:131132 if amt:133 return data134135 if not decode_content or not decoder:136 if cache_content:137 self._body = data138139 return data140141 try:142 data = decoder(data)143 except IOError:144 raise HTTPError("Received response with content-encoding: %s, but "145 "failed to decode it." % content_encoding)146147 if cache_content:148 self._body = data149150 return data151152 finally:153154 if self._original_response and self._original_response.isclosed():155 self.release_conn()156157 @staticmethod158 def from_httplib(r, **response_kw):159 """160 Given an :class:`httplib.HTTPResponse` instance ``r``, return a161 corresponding :class:`urllib3.response.HTTPResponse` object.162163 Remaining parameters are passed to the HTTPResponse constructor, along164 with ``original_response=r``.165 """166167 return HTTPResponse(body=r,168 headers=dict(r.getheaders()),169 status=r.status,170 version=r.version,171 reason=r.reason,172 strict=r.strict,173 original_response=r,174 **response_kw)175176 # Backwards-compatibility methods for httplib.HTTPResponse177 def getheaders(self):178 return self.headers179180 def getheader(self, name, default=None):181 return self.headers.get(name, default)
modified:requests/packages/__init__.py+1 added-1 removed
1from __future__ import absolute_import23from . import poster3from . import urllib3
modified:requests/__init__.py+6 added-6 removed
13 unmodified lines
1415"""1617__title__ = 'requests'18__version__ = '0.7.6'19__build__ = 0x00070618__version__ = '0.8.0'19__build__ = 0x00080020__author__ = 'Kenneth Reitz'21__license__ = 'ISC'22__copyright__ = 'Copyright 2011 Kenneth Reitz'232425from . import utils26from .models import Request, Response27from .api import request, get, head, post, patch, put, delete28from .sessions import session27from .api import request, get, head, post, patch, put, delete, options28from .sessions import session, Session29from .status_codes import codes30from .exceptions import (31 RequestException, AuthenticationError, Timeout, URLRequired,32 TooManyRedirects31 RequestException, Timeout, URLRequired,32 TooManyRedirects, HTTPError, ConnectionError33)
modified:requests/api.py+32 added-10 removed
11 unmodified lines
12"""1314from .sessions import session1516__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')161817def request(method, url,18 params=None,19 data=None,20 headers=None,
4 unmodified lines
25 allow_redirects=False,26 proxies=None,27 hooks=None,28 return_response=True,29 prefetch=False,30 config=None):31 """Constructs and sends a :class:`Request <Request>`.32 Returns :class:`Response <Response>` object.33
13 unmodified lines
47 """4849 s = session()50 return s.request(52 method, url, params, data, headers, cookies, files, auth,53 timeout, allow_redirects, proxies, hooks, return_response,54 config51 method=method,52 url=url,53 params=params,54 data=data,55 headers=headers,56 cookies=cookies,57 files=files,58 auth=auth,59 timeout=timeout,60 allow_redirects=allow_redirects,61 proxies=proxies,62 hooks=hooks,63 return_response=return_response,64 config=config,65 prefetch=prefetch66 )676869
4 unmodified lines
74 :param **kwargs: Optional arguments that ``request`` takes.75 """7677 kwargs.setdefault('allow_redirects', True)67 return request('GET', url, **kwargs)78 return request('get', url, **kwargs)798081def options(url, **kwargs):82 """Sends a OPTIONS request. Returns :class:`Response` object.8384 :param url: URL for the new :class:`Request` object.85 :param **kwargs: Optional arguments that ``request`` takes.86 """8788 kwargs.setdefault('allow_redirects', True)89 return request('options', url, **kwargs)909192def head(url, **kwargs):93 """Sends a HEAD request. Returns :class:`Response` object.9495 :param url: URL for the new :class:`Request` object.96 :param **kwargs: Optional arguments that ``request`` takes.97 """9899 kwargs.setdefault('allow_redirects', True)78 return request('HEAD', url, **kwargs)100 return request('head', url, **kwargs)10110281def post(url, data='', **kwargs):103def post(url, data=None, **kwargs):104 """Sends a POST request. Returns :class:`Response` object.105106 :param url: URL for the new :class:`Request` object.107 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
2 unmodified lines
110111 return request('post', url, data=data, **kwargs)11211392def put(url, data='', **kwargs):114def put(url, data=None, **kwargs):115 """Sends a PUT request. Returns :class:`Response` object.116117 :param url: URL for the new :class:`Request` object.118 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
2 unmodified lines
121122 return request('put', url, data=data, **kwargs)123124103def patch(url, data='', **kwargs):125def patch(url, data=None, **kwargs):126 """Sends a PATCH request. Returns :class:`Response` object.127128 :param url: URL for the new :class:`Request` object.129 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
14 unmodified lines
modified:requests/async.py+13 added-5 removed
10 unmodified lines
1112try:13 import gevent14 from gevent import monkey as curious_george15 from gevent.pool import Pool16except ImportError:17 raise RuntimeError('Gevent is required for requests.async.')1819# Monkey-patch.20curious_george.patch_all(thread=False)2122from . import api22from .hooks import dispatch_hook232425__all__ = (26 'map',27 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'27 'get', 'options', 'head', 'post', 'put', 'patch', 'delete', 'request'28)293031def patched(f):
1 unmodified line
3334 def wrapped(*args, **kwargs):3536 kwargs['return_response'] = False37 kwargs['prefetch'] = True3839 return f(*args, **kwargs)4041 return wrapped
11 unmodified lines
535455# Patched requests.api functions.56get = patched(api.get)57options = patched(api.options)58head = patched(api.head)59post = patched(api.post)60put = patched(api.put)61patch = patched(api.patch)62delete = patched(api.delete)63request = patched(api.request)646564def map(requests, prefetch=True):66def map(requests, prefetch=True, size=None):67 """Concurrently converts a list of Requests to Responses.6869 :param requests: a collection of Request objects.70 :param prefetch: If False, the content will not be downloaded immediately.71 :param size: Specifies the number of requests to make at a time. If None, no throttling occurs.72 """7374 if size:75 pool = Pool(size)76 pool.map(send, requests)77 pool.join()78 else:71 jobs = [gevent.spawn(send, r) for r in requests]72 gevent.joinall(jobs)79 jobs = [gevent.spawn(send, r) for r in requests]80 gevent.joinall(jobs)8182 if prefetch:83 [r.response.content for r in requests]84
5 unmodified lines
modified:requests/defaults.py+16 added-13 removed
4 unmodified lines
5~~~~~~~~~~~~~~~~~67This module provides the Requests configuration defaults.89settings parameters:9Configurations:1011- :base_headers: - Sets default User-Agent to `python-requests.org`12- :accept_gzip: - Whether or not to accept gzip-compressed data13- :proxies: - http proxies?14- :verbose: - display verbose information?15- :timeout: - timeout time until request terminates16- :max_redirects: - maximum number of allowed redirects?17- :decode_unicode: - whether or not to accept unicode?11:base_headers: Default HTTP headers.12:verbose: Stream to write request logging to.13:timeout: Seconds until request timeout.14:max_redirects: Maximum njumber of redirects allowed within a request.15:decode_unicode: Decode unicode responses automatically?16:keep_alive: Reuse HTTP Connections?17:max_retries: The number of times a request should be retried in the event of a connection failure.18:safe_mode: If true, Requests will catch all errors.19:pool_maxsize: The maximium size of an HTTP connection pool.20:pool_connections: The number of active HTTP connection pools to use.2122"""2324from . import __version__
6 unmodified lines
31 'Accept-Encoding': ', '.join(('identity', 'deflate', 'compress', 'gzip')),32 'Accept': '*/*'33}3432defaults['proxies'] = {}35defaults['verbose'] = None34defaults['timeout'] = None36defaults['max_redirects'] = 3037defaults['decode_unicode'] = True37defaults['timeout_fallback'] = True38# defaults['keep_alive'] = True39# defaults['max_connections'] = 1038defaults['pool_connections'] = 1039defaults['pool_maxsize'] = 1040defaults['max_retries'] = 041defaults['safe_mode'] = False42defaults['keep_alive'] = True
modified:requests/exceptions.py+5 added-2 removed
10 unmodified lines
11class RequestException(Exception):12 """There was an ambiguous exception that occurred while handling your13 request."""1415class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15class HTTPError(RequestException):16 """An HTTP error occured."""1718class ConnectionError(RequestException):19 """A Connection error occured."""2021class Timeout(RequestException):22 """The request timed out."""2324class URLRequired(RequestException):
4 unmodified lines
modified:requests/models.py+193 added-127 removed
11# -*- coding: utf-8 -*-23"""4requests.models5~~~~~~~~~~~~~~~67This module contains the primary objects that power Requests.8"""910import urllib11import urllib212import socket11import zlib1213from Cookie import SimpleCookie14from urlparse import urlparse, urlunparse, urljoin15from datetime import datetime1617from .auth import dispatch as auth_dispatch18from .hooks import dispatch_hook19from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers20from .status_codes import codes24from .exceptions import Timeout, URLRequired, TooManyRedirects25from .monkeys import Request as _Request26from .monkeys import HTTPRedirectHandler21from .packages.urllib3.exceptions import MaxRetryError22from .packages.urllib3.exceptions import SSLError as _SSLError23from .packages.urllib3.exceptions import HTTPError as _HTTPError24from .packages.urllib3 import connectionpool, poolmanager25from .packages.urllib3.filepost import encode_multipart_formdata26from .exceptions import (27 Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28from .utils import (28 dict_from_cookiejar, get_unicode_from_response,29 stream_decode_response_unicode, decode_gzip, stream_decode_gzip)29 get_unicode_from_response, stream_decode_response_unicode,30 decode_gzip, stream_decode_gzip, guess_filename)313233REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)34
17 unmodified lines
52 redirect=False,53 allow_redirects=False,54 proxies=None,55 hooks=None,55 config=None):56 config=None,57 _poolmanager=None):5859 #: Float describes the timeout of the request.60 # (Use socket.setdefaulttimeout() as fallback)61 self.timeout = timeout
1 unmodified line
63 #: Request URL.64 self.url = url6566 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.65 self.headers = headers67 self.headers = dict(headers or [])6869 #: Dictionary of files to multipart upload (``{filename: content}``).70 self.files = files71
6 unmodified lines
7879 #: Dictionary or byte of querystring data to attach to the80 #: :class:`Request <Request>`.81 self.params = None82 self.params = dict(params or [])8384 #: True if :class:`Request <Request>` is part of a redirect chain (disables history85 #: and HTTPError storage).86 self.redirect = redirect
1 unmodified line
88 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)89 self.allow_redirects = allow_redirects9091 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})89 self.proxies = proxies92 self.proxies = dict(proxies or [])9394 self.data, self._enc_data = self._encode_params(data)95 self.params, self._enc_params = self._encode_params(params)96
5 unmodified lines
102 self._auth = auth103 self.auth = auth_dispatch(auth)104105 #: CookieJar to attach to :class:`Request <Request>`.103 self.cookies = cookies106 self.cookies = dict(cookies or [])107108 #: Dictionary of configurations for this request.106 self.config = config109 self.config = dict(config or [])110111 #: True if Request has been sent.112 self.sent = False113114 #: Event-handling hooks.115 self.hooks = hooks116117 #: Session.118 self.session = None119120 if headers:121 headers = CaseInsensitiveDict(self.headers)122 else:123 headers = CaseInsensitiveDict()
2 unmodified lines
126 if k not in headers:127 headers[k] = v128129 self.headers = headers130 self._poolmanager = _poolmanager131132 # Pre-request hook.133 r = dispatch_hook('pre_request', hooks, self)134 self.__dict__.update(r.__dict__)
2 unmodified lines
137 def __repr__(self):138 return '<Request [%s]>' % (self.method)139140134 def _get_opener(self):135 """Creates appropriate opener object for urllib2."""136137 _handlers = []138139 if self.cookies is not None:140 _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))141142 if self.proxies:143 _handlers.append(urllib2.ProxyHandler(self.proxies))144145 _handlers.append(HTTPRedirectHandler)146147 if not _handlers:148 return urllib2.urlopen149150 if self.data or self.files:151 _handlers.extend(get_handlers())152153 opener = urllib2.build_opener(*_handlers)154155 if self.headers:156 # Allow default headers in the opener to be overloaded157 normal_keys = [k.capitalize() for k in self.headers]158 for key, val in opener.addheaders[:]:159 if key not in normal_keys:160 continue161 # Remove it, we have a value to take its place162 opener.addheaders.remove((key, val))163164 return opener.open165166141 def _build_response(self, resp, is_error=False):142 """Build internal :class:`Response <Response>` object143 from given response.144 """
1 unmodified line
146147 def build(resp):148149 response = Response()150151 # Pass settings over.152 response.config = self.config177 response.status_code = getattr(resp, 'code', None)153179 try:180 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))181 response.raw = resp154 if resp:155183 if self.cookies:184 response.cookies = dict_from_cookiejar(self.cookies)156 # Fallback to None if there's no staus_code, for whatever reason.157 response.status_code = getattr(resp, 'status', None)158159 # Make headers case-insensitive.160 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))161187 except AttributeError:188 pass162 # Start off with our local cookies.163 cookies = self.cookies or dict()164165 # Add new cookies from the server.166 if 'set-cookie' in response.headers:167 cookie_header = response.headers['set-cookie']168169 c = SimpleCookie()170 c.load(cookie_header)171172 for k,v in c.items():173 cookies.update({k: v.value})174175 # Save cookies in Response.176 response.cookies = cookies177178 # Save original resopnse for later.179 response.raw = resp180181 if is_error:182 response.error = resp183193 response.url = getattr(resp, 'url', None)184 response.url = self._build_url()185186 return response187188189 history = []190191 r = build(resp)192 cookies = self.cookies193 self.cookies.update(r.cookies)194195 if r.status_code in REDIRECT_STATI and not self.redirect:196197 while (198 ('location' in r.headers) and199 ((r.status_code is codes.see_other) or (self.allow_redirects))200 ):201209 r.raw.close()210202 if not len(history) < self.config.get('max_redirects'):203 raise TooManyRedirects()204205 history.append(r)
15 unmodified lines
221 method = 'GET'222 else:223 method = self.method224225 # Remove the cookie headers that were sent.226 headers = self.headers227 try:228 del headers['Cookie']229 except KeyError:230 pass231232 request = Request(233 url=url,236 headers=self.headers,234 headers=headers,235 files=self.files,236 method=method,239 # data=self.data,240 # params=self.params,237 params=self.session.params,238 auth=self._auth,242 cookies=self.cookies,239 cookies=cookies,240 redirect=True,244 config=self.config241 config=self.config,242 _poolmanager=self._poolmanager243 )244245 request.send()246 cookies.update(request.response.cookies)247 r = request.response248 self.cookies.update(r.cookies)249250 r.history = history251252 self.response = r253 self.response.request = self254 self.response.cookies.update(self.cookies)255256257 @staticmethod258 def _encode_params(data):
6 unmodified lines
265 Otherwise, assumes the data is already encoded appropriately, and266 returns it twice.267 """268269 if hasattr(data, '__iter__'):270 data = dict(data)271272 if hasattr(data, 'items'):273 result = []274 for k, vs in data.items():275 for v in isinstance(vs, list) and vs or [vs]:
6 unmodified lines
282283 def _build_url(self):284 """Build the actual URL to use."""285286 if not self.url:287 raise URLRequired()288289 # Support for unicode domain names and paths.290 scheme, netloc, path, params, query, fragment = urlparse(self.url)291292 if not scheme:293 raise ValueError()294295 netloc = netloc.encode('idna')296297 if isinstance(path, unicode):298 path = path.encode('utf-8')299300 path = urllib.quote(urllib.unquote(path))301 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))302303 if self._enc_params:
4 unmodified lines
308 else:309 return self.url310311298 def send(self, anyway=False):312 def send(self, anyway=False, prefetch=False):313 """Sends the request. Returns True of successful, false if not.314 If there was an HTTPError during transmission,315 self.response.status_code will contain the HTTPError code.316
2 unmodified lines
319 :param anyway: If True, request will be sent, even if it has320 already been sent.321 """322309 # Some people...310 if not self.url:311 raise URLRequired312323 # Logging324 if self.config.get('verbose'):325 self.config.get('verbose').write('%s %s %s\n' % (326 datetime.now().isoformat(), self.method, self.url
1 unmodified line
328329 # Build the URL330 url = self._build_url()331322 # Attach uploaded files.332 # Nottin' on you.333 body = None334 content_type = None335336 # Multi-part file uploads.337 if self.files:324 register_openers()338 if not isinstance(self.data, basestring):339326 # Add form-data to the multipart.327 if self.data:328 self.files.update(self.data)340 try:341 fields = self.data.copy()342 except AttributeError:343 fields = dict(self.data)344330 data, headers = multipart_encode(self.files)345 for (k, v) in self.files.items():346 fields.update({k: (guess_filename(k) or k, v.read())})347348 (body, content_type) = encode_multipart_formdata(fields)349 else:350 pass351 # TODO: Conflict?352 else:333 data = self._enc_data334 headers = {}353 if self.data:354355 body = self._enc_data356 if isinstance(self.data, basestring):357 content_type = None358 else:359 content_type = 'application/x-www-form-urlencoded'360361 # Add content-type if it wasn't explicitly provided.362 if (content_type) and (not 'content-type' in self.headers):363 self.headers['Content-Type'] = content_type364365366 if self.auth:367 auth_func, auth_args = self.auth368369 # Allow auth to make its changes.370 r = auth_func(self, *auth_args)371372 # Update self to reflect the auth changes.373 self.__dict__.update(r.__dict__)374343 # Build the Urllib2 Request.344 req = _Request(url, data=data, headers=headers, method=self.method)375 _p = urlparse(url)376 proxy = self.proxies.get(_p.scheme)377346 # Add the headers to the request.347 if self.headers:348 for k,v in self.headers.iteritems():349 req.add_header(k, v)378 if proxy:379 conn = poolmanager.proxy_from_url(url)380 else:381 # Check to see if keep_alive is allowed.382 if self.config.get('keep_alive'):383 conn = self._poolmanager.connection_from_url(url)384 else:385 conn = connectionpool.connection_from_url(url)386387 if not self.sent or anyway:388353 try:354 opener = self._get_opener()355 try:389 if self.cookies:390357 resp = opener(req, timeout=self.timeout)391 # Skip if 'cookie' header is explicitly set.392 if 'cookie' not in self.headers:393359 except TypeError, err:360 # timeout argument is new since Python v2.6361 if not 'timeout' in str(err):362 raise394 # Simple cookie with our dict.395 c = SimpleCookie()396 for (k, v) in self.cookies.items():397 c[k] = v398364 if self.config.get('timeout_fallback'):365 # fall-back and use global socket timeout (This is not thread-safe!)366 old_timeout = socket.getdefaulttimeout()367 socket.setdefaulttimeout(self.timeout)399 # Turn it into a header.400 cookie_header = c.output(header='').strip()401369 resp = opener(req)402 # Attach Cookie header to request.403 self.headers['Cookie'] = cookie_header404371 if self.config.get('timeout_fallback'):372 # restore global timeout373 socket.setdefaulttimeout(old_timeout)405 try:406 # Send the request.407375 if self.cookies is not None:376 self.cookies.extract_cookies(resp, req)408 r = conn.urlopen(409 method=self.method,410 url=url,411 body=body,412 headers=self.headers,413 redirect=False,414 assert_same_host=False,415 preload_content=prefetch,416 decode_content=False,417 retries=self.config.get('max_retries', 0),418 timeout=self.timeout,419 )420378 except (urllib2.HTTPError, urllib2.URLError), why:379 if hasattr(why, 'reason'):380 if isinstance(why.reason, socket.timeout):381 why = Timeout(why)382 elif isinstance(why.reason, socket.error):383 why = Timeout(why)421385 self._build_response(why, is_error=True)422 except MaxRetryError, e:423 if not self.config.get('safe_mode', False):424 raise ConnectionError(e)425 else:426 r = None427387 else:388 self._build_response(resp)389 self.response.ok = True428 except (_SSLError, _HTTPError), e:429 if not self.config.get('safe_mode', False):430 raise Timeout('Request timed out.')431432 self._build_response(r)433392 self.sent = self.response.ok434 # Response manipulation hook.435 self.response = dispatch_hook('response', self.hooks, self.response)436394 # Response manipulation hook.395 self.response = dispatch_hook('response', self.hooks, self.response)437 # Post-request hook.438 r = dispatch_hook('post_request', self.hooks, self)439 self.__dict__.update(r.__dict__)440397 # Post-request hook.398 r = dispatch_hook('post_request', self.hooks, self)399 self.__dict__.update(r.__dict__)441 # If prefetch is True, mark content as consumed.442 if prefetch:443 self.response._content_consumed = True444401 return self.sent445 return self.sent446447448class Response(object):449 """The core :class:`Response <Response>` object. All
20 unmodified lines
470471 #: Final URL location of Response.472 self.url = None473430 #: True if no :attr:`error` occurred.431 self.ok = False432474 #: Resulting :class:`HTTPError` of request, if one occurred.475 self.error = None476477 #: A list of :class:`Response <Response>` objects from
4 unmodified lines
482 #: The :class:`Request <Request>` that created the Response.483 self.request = None484485 #: A dictionary of Cookies the server sent back.445 self.cookies = None486 self.cookies = {}487488 #: Dictionary of configurations for this request.448 self.config = None489 self.config = {}490491492 def __repr__(self):493 return '<Response [%s]>' % (self.status_code)494454495 def __nonzero__(self):496 """Returns true if :attr:`status_code` is 'OK'."""497 return self.ok498458 return not self.error499 @property500 def ok(self):501 try:502 self.raise_for_status()503 except HTTPError:504 return False505 return True506507508 def iter_content(self, chunk_size=10 * 1024, decode_unicode=None):509 """Iterates over the response data. This avoids reading the content510 at once into memory for large responses. The chunk size is the number511 of bytes it should read into memory. This is not necessarily the512 length of each item returned as decoding can take place.513 """514 if self._content_consumed:467 raise RuntimeError('The content for this response was '468 'already consumed')515 raise RuntimeError(516 'The content for this response was already consumed'517 )518519 def generate():520 while 1:521 chunk = self.raw.read(chunk_size)522 if not chunk:523 break524 yield chunk525 self._content_consumed = True526527 gen = generate()528529 if 'gzip' in self.headers.get('content-encoding', ''):530 gen = stream_decode_gzip(gen)531532 if decode_unicode is None:533 decode_unicode = self.config.get('decode_unicode')534535 if decode_unicode:536 gen = stream_decode_response_unicode(gen, self)537538 return gen539540541 @property542 def content(self):543 """Content of the response, in bytes or unicode544 (if available).
29 unmodified lines
574575576 def raise_for_status(self):577 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""578579 if self.error:580 raise self.error581582 if (self.status_code >= 300) and (self.status_code < 400):583 raise HTTPError('%s Redirection' % self.status_code)584585 elif (self.status_code >= 400) and (self.status_code < 500):586 raise HTTPError('%s Client Error' % self.status_code)587588 elif (self.status_code >= 500) and (self.status_code < 600):589 raise HTTPError('%s Server Error' % self.status_code)590591
modified:requests/sessions.py+53 added-27 removed
7 unmodified lines
8requests (cookies, auth, proxies).910"""1112import cookielib1312from .defaults import defaults13from .models import Request14from .hooks import dispatch_hook17from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand15from .utils import header_expand16from .packages.urllib3.poolmanager import PoolManager171819def merge_kwargs(local_kwarg, default_kwarg):20 """Merges kwarg dictionaries.
41 unmodified lines
62 timeout=None,63 proxies=None,64 hooks=None,65 params=None,67 config=None,68 keep_alive=True):66 config=None):6768 self.headers = headers or {}69 self.cookies = cookies or {}70 self.auth = auth
1 unmodified line
72 self.proxies = proxies or {}73 self.hooks = hooks or {}74 self.params = params or {}75 self.config = config or {}78 self.keep_alive = keep_alive7677 for (k, v) in defaults.items():78 self.config.setdefault(k, v)7980 self.poolmanager = PoolManager(81 num_pools=self.config.get('pool_connections'),82 maxsize=self.config.get('pool_maxsize')83 )8485 # Set up a CookieJar to be used by default84 self.cookies = cookielib.FileCookieJar()86 self.cookies = {}8788 # Add passed cookies in.89 if cookies is not None:90 self.cookies.update(cookies)9192 def __repr__(self):93 return '<requests-client at 0x%x>' % (id(self))9495 def __enter__(self):
13 unmodified lines
109 allow_redirects=False,110 proxies=None,111 hooks=None,112 return_response=True,107 config=None):113 config=None,114 prefetch=False):115116 """Constructs and sends a :class:`Request <Request>`.117 Returns :class:`Response <Response>` object.118
9 unmodified lines
128 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.129 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.130 :param return_response: (optional) If False, an un-sent Request object will returned.131 :param config: (optional) A configuration dictionary.132 :param prefetch: (optional) if ``True``, the response content will be immediately downloaded.133 """134135 method = str(method).upper()136129 if cookies is None:130 cookies = {}137 # Default empty dicts for dict params.138 cookies = {} if cookies is None else cookies139 data = {} if data is None else data140 files = {} if files is None else files141 headers = {} if headers is None else headers142 params = {} if params is None else params143132 if isinstance(cookies, dict):133 cookies = add_dict_to_cookiejar(self.cookies, cookies)134135 cookies = cookiejar_from_dict(cookies)136137 # Expand header values144 # Expand header values.145 if headers:146 for k, v in headers.items() or {}:147 headers[k] = header_expand(v)148
9 unmodified lines
158 hooks=hooks,159 timeout=timeout,160 allow_redirects=allow_redirects,161 proxies=proxies,155 config=config162 config=config,163 _poolmanager=self.poolmanager164 )165166 # Merge local kwargs with session kwargs.167 for attr in self.__attrs__:168 session_val = getattr(self, attr, None)169 local_val = args.get(attr)170171 args[attr] = merge_kwargs(local_val, session_val)172164173 # Arguments manipulation hook.174 args = dispatch_hook('args', args['hooks'], args)175176 # Create the (empty) response.177 r = Request(**args)178179 # Give the response some context.180 r.session = self181182 # Don't send if asked nicely.183 if not return_response:184 return r185186 # Send the HTTP Request.175 r.send()187 r.send(prefetch=prefetch)188189 # Send any cookies back up the to the session.190 self.cookies.update(r.response.cookies)191192 # Return the response.193 return r.response194195196 def get(self, url, **kwargs):
3 unmodified lines
200 :param **kwargs: Optional arguments that ``request`` takes.201 """202203 kwargs.setdefault('allow_redirects', True)188 return self.request('GET', url, **kwargs)204 return self.request('get', url, **kwargs)205206207 def options(self, url, **kwargs):208 """Sends a OPTIONS request. Returns :class:`Response` object.209210 :param url: URL for the new :class:`Request` object.211 :param **kwargs: Optional arguments that ``request`` takes.212 """213214 kwargs.setdefault('allow_redirects', True)215 return self.request('options', url, **kwargs)216217218 def head(self, url, **kwargs):219 """Sends a HEAD request. Returns :class:`Response` object.220221 :param url: URL for the new :class:`Request` object.222 :param **kwargs: Optional arguments that ``request`` takes.223 """224225 kwargs.setdefault('allow_redirects', True)199 return self.request('HEAD', url, **kwargs)226 return self.request('head', url, **kwargs)227228202 def post(self, url, data='', **kwargs):229 def post(self, url, data=None, **kwargs):230 """Sends a POST request. Returns :class:`Response` object.231232 :param url: URL for the new :class:`Request` object.233 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
2 unmodified lines
236237 return self.request('post', url, data=data, **kwargs)238239213 def put(self, url, data='', **kwargs):240 def put(self, url, data=None, **kwargs):241 """Sends a PUT request. Returns :class:`Response` object.242243 :param url: URL for the new :class:`Request` object.244 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
2 unmodified lines
247248 return self.request('put', url, data=data, **kwargs)249250224 def patch(self, url, data='', **kwargs):251 def patch(self, url, data=None, **kwargs):252 """Sends a PATCH request. Returns :class:`Response` object.253254 :param url: URL for the new :class:`Request` object.255 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.256 :param **kwargs: Optional arguments that ``request`` takes.257 """258232 return self.request('patch', url, data='', **kwargs)259 return self.request('patch', url, data=data, **kwargs)260261262 def delete(self, url, **kwargs):263 """Sends a DELETE request. Returns :class:`Response` object.
4 unmodified lines
268269 return self.request('delete', url, **kwargs)270271245272def session(**kwargs):273 """Returns a :class:`Session` for context-management."""274249 return Session(**kwargs)275 return Session(**kwargs)
modified:requests/structures.py+1 added
6 unmodified lines
7Data structures that power Requests.89"""101112class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary1415 For example, ``headers['content-encoding']`` will return the
51 unmodified lines
modified:requests/utils.py+6 added
18 unmodified lines
1920from urllib2 import parse_http_list as _parse_list_header212223def guess_filename(obj):24 """Tries to guess the filename of the given object."""25 name = getattr(obj, 'name', None)26 if name and name[0] != '<' and name[-1] != '>':27 return name2829# From mitsuhiko/werkzeug (used with permission).30def parse_list_header(value):31 """Parse lists as described by RFC 2068 Section 2.32
337 unmodified lines
modified:AUTHORS+10 added-1 removed
5 unmodified lines
67- Kenneth Reitz <me@kennethreitz.com>8910Urllib311```````1213- Andrey Petrov <andrey.petrov@shazow.net>141516Patches and Suggestions17```````````````````````1819- Various Pocoo Members
34 unmodified lines
54- Fredrik Möllerstrand55- Daniel Hengeveld56- Dan Head57- Bruno Renié52- David Fischer58- David Fischer59- Joseph McCullough60- Juergen Brendel61- Juan Riaza
modified:HISTORY.rst+15 added
1History2-------3450.8.0 (2011-11-13)6++++++++++++++++++78* Keep-alive support!9* Complete removal of Urllib210* Complete removal of Poster11* Complete removal of CookieJars12* New ConnectionError raising13* Safe_mode for error catching14* prefetch parameter for request methods15* OPTION method16* Async pool size throttling17* File uploads send real names18190.7.6 (2011-11-07)20++++++++++++++++++2122* Digest authentication bugfix (attach query data to path)
234 unmodified lines
modified:README.rst+1 added-1 removed
25 unmodified lines
2627Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,28**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,29multipart files, and parameters with simple Python dictionaries, and access the30response data in the same way. It's powered by urllib2, but it does30response data in the same way. It's powered by httplib, but it does31all the hard work and crazy hacks for you.323334Features
68 unmodified lines
modified:setup.py+1 added-1 removed
35 unmodified lines
36 url='http://python-requests.org',37 packages= [38 'requests',39 'requests.packages',40 'requests.packages.poster'40 'requests.packages.urllib3'41 ],42 install_requires=required,43 license='ISC',44 classifiers=(
12 unmodified lines
modified:test_requests.py+64 added-45 removed
2 unmodified lines
34from __future__ import with_statement56import time7import cookielib7import os8import unittest910import requests11import envoy13from urllib2 import HTTPError12from requests import HTTPError1314try:15 import omnijson as json16except ImportError:
39 unmodified lines
5657 def tearDown(self):58 """Teardown."""59 # self.httpbin.kill()60 pass616263 def test_entry_points(self):63 import requests6465 requests.session66 requests.session().get67 requests.session().head
166 unmodified lines
234235 for service in SERVICES:236237 r = requests.get(service('status', '404'))238 # print r.status_code239 # r.raise_for_status()240 self.assertEqual(r.ok, False)241242243 def test_status_raising(self):
4 unmodified lines
248 self.assertFalse(r.error)249 r.raise_for_status()250251250 def test_cookie_jar(self):251252 jar = cookielib.CookieJar()253 self.assertFalse(jar)254255 url = httpbin('cookies', 'set', 'requests_cookie', 'awesome')256 r = requests.get(url, cookies=jar)257 self.assertTrue(jar)258259 cookie_found = False260 for cookie in jar:261 if cookie.name == 'requests_cookie':262 self.assertEquals(cookie.value, 'awesome')263 cookie_found = True264 self.assertTrue(cookie_found)265266 r = requests.get(httpbin('cookies'), cookies=jar)267 self.assertTrue('awesome' in r.content)268269252 def test_decompress_gzip(self):253254 r = requests.get(httpbin('gzip'))255 r.content.decode('ascii')
49 unmodified lines
305306 rbody = json.loads(r.content)307 # Body wasn't valid url encoded data, so the server returns None as308 # "form" and the raw body as "data".327 self.assertEquals(rbody.get('form'), None)309 self.assertEquals(rbody.get('form'), {})310 self.assertEquals(rbody.get('data'), 'fooaowpeuf')311312313 def test_urlencoded_post_querystring(self):
10 unmodified lines
324 self.assertEquals(rbody.get('form'), {}) # No form supplied325 self.assertEquals(rbody.get('data'), '')326327346 def test_nonurlencoded_post_querystring(self):347348 for service in SERVICES:349350 r = requests.post(service('post'), params='fooaowpeuf')351352 self.assertEquals(r.status_code, 200)353 self.assertEquals(r.headers['content-type'], 'application/json')354 self.assertEquals(r.url, service('post?fooaowpeuf'))355356 rbody = json.loads(r.content)357 self.assertEquals(rbody.get('form'), {}) # No form supplied358 self.assertEquals(rbody.get('data'), '')359360328 def test_urlencoded_post_query_and_data(self):329330 for service in SERVICES:331
10 unmodified lines
342 self.assertEquals(rbody.get('form'), dict(test2='foobar'))343 self.assertEquals(rbody.get('data'), '')344345379 def test_nonurlencoded_post_query_and_data(self):346 def test_nonurlencoded_postdata(self):347348 for service in SERVICES:349383 r = requests.post(service('post'),384 params='fooaowpeuf', data="foobar")350 r = requests.post(service('post'), data="foobar")351352 self.assertEquals(r.status_code, 200)353 self.assertEquals(r.headers['content-type'], 'application/json')388 self.assertEquals(r.url, service('post?fooaowpeuf'))354355 rbody = json.loads(r.content)356392 self.assertEquals(rbody.get('form'), None)357 self.assertEquals(rbody.get('form'), {})358 self.assertEquals(rbody.get('data'), 'foobar')359360361 # def test_idna(self):
103 unmodified lines
465 assert new_heads['User-agent'] in r3.content466467 self.assertEqual(r2.status_code, 200)468469 def test_session_persistent_cookies(self):470471 s = requests.session()472473 # Internally dispatched cookies are sent.474 _c = {'kenneth': 'reitz', 'bessie': 'monke'}475 r = s.get(httpbin('cookies'), cookies=_c)476 r = s.get(httpbin('cookies'))477478 # Those cookies persist transparently.479 c = json.loads(r.content).get('cookies')480 assert c == _c481482 # Double check.483 r = s.get(httpbin('cookies'), cookies={})484 c = json.loads(r.content).get('cookies')485 assert c == _c486487 # Remove a cookie by setting it's value to None.488 r = s.get(httpbin('cookies'), cookies={'bessie': None})489 c = json.loads(r.content).get('cookies')490 del _c['bessie']491 assert c == _c492493 # Test session-level cookies.494 s = requests.session(cookies=_c)495 r = s.get(httpbin('cookies'))496 c = json.loads(r.content).get('cookies')497 assert c == _c498499 # Have the server set a cookie.500 r = s.get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True)501 c = json.loads(r.content).get('cookies')502503 assert 'k' in c504505 # And server-set cookie persistience.506 r = s.get(httpbin('cookies'))507 c = json.loads(r.content).get('cookies')508509 assert 'k' in c510511512513 def test_session_persistent_params(self):514515 params = {'a': 'a_test'}516
20 unmodified lines
537 assert params3['b'] in r3.content538 assert params3['c'] in r3.content539540 def test_invalid_content(self):541 # WARNING: if you're using a terrible DNS provider (comcast),542 # this will fail.543 try:544 hah = 'http://somedomainthatclearlydoesntexistg.com'545 r = requests.get(hah, allow_redirects=False)546 except requests.ConnectionError:547 pass # \o/548 else:549 assert False550534 r = requests.get('http://somedomainthatclearlydoesntexistg.com')551552 config = {'safe_mode': True}553 r = requests.get(hah, allow_redirects=False, config=config)554 assert r.content == None555556557if __name__ == '__main__':
1 unmodified line