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, 14a7988 · Browse files · 37 files+3160 added−1021 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+3160 added−1021 removed

  • other:+3160 added−1021 removed

37 files+3160 added−1021 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/__collections.py+991 added
1from __future__ import with_statement234# Copyright 2007 Google, Inc. All Rights Reserved.5# Licensed to PSF under a Contributor Agreement.67"""Abstract Base Classes (ABCs) according to PEP 3119."""89import types1011from _weakref import ref1213__all__ = ['WeakSet']141516class _IterationGuard(object):17 # This context manager registers itself in the current iterators of the18 # weak container, such as to delay all removals until the context manager19 # exits.20 # This technique should be relatively thread-safe (since sets are).2122 def __init__(self, weakcontainer):23 # Don't create cycles24 self.weakcontainer = ref(weakcontainer)2526 def __enter__(self):27 w = self.weakcontainer()28 if w is not None:29 w._iterating.add(self)30 return self3132 def __exit__(self, e, t, b):33 w = self.weakcontainer()34 if w is not None:35 s = w._iterating36 s.remove(self)37 if not s:38 w._commit_removals()394041class WeakSet(object):42 def __init__(self, data=None):43 self.data = set()44 def _remove(item, selfref=ref(self)):45 self = selfref()46 if self is not None:47 if self._iterating:48 self._pending_removals.append(item)49 else:50 self.data.discard(item)51 self._remove = _remove52 # A list of keys to be removed53 self._pending_removals = []54 self._iterating = set()55 if data is not None:56 self.update(data)5758 def _commit_removals(self):59 l = self._pending_removals60 discard = self.data.discard61 while l:62 discard(l.pop())6364 def __iter__(self):65 with _IterationGuard(self):66 for itemref in self.data:67 item = itemref()68 if item is not None:69 yield item7071 def __len__(self):72 return sum(x() is not None for x in self.data)7374 def __contains__(self, item):75 try:76 wr = ref(item)77 except TypeError:78 return False79 return wr in self.data8081 def __reduce__(self):82 return (self.__class__, (list(self),),83 getattr(self, '__dict__', None))8485 __hash__ = None8687 def add(self, item):88 if self._pending_removals:89 self._commit_removals()90 self.data.add(ref(item, self._remove))9192 def clear(self):93 if self._pending_removals:94 self._commit_removals()95 self.data.clear()9697 def copy(self):98 return self.__class__(self)99100 def pop(self):101 if self._pending_removals:102 self._commit_removals()103 while True:104 try:105 itemref = self.data.pop()106 except KeyError:107 raise KeyError('pop from empty WeakSet')108 item = itemref()109 if item is not None:110 return item111112 def remove(self, item):113 if self._pending_removals:114 self._commit_removals()115 self.data.remove(ref(item))116117 def discard(self, item):118 if self._pending_removals:119 self._commit_removals()120 self.data.discard(ref(item))121122 def update(self, other):123 if self._pending_removals:124 self._commit_removals()125 if isinstance(other, self.__class__):126 self.data.update(other.data)127 else:128 for element in other:129 self.add(element)130131 def __ior__(self, other):132 self.update(other)133 return self134135 # Helper functions for simple delegating methods.136 def _apply(self, other, method):137 if not isinstance(other, self.__class__):138 other = self.__class__(other)139 newdata = method(other.data)140 newset = self.__class__()141 newset.data = newdata142 return newset143144 def difference(self, other):145 return self._apply(other, self.data.difference)146 __sub__ = difference147148 def difference_update(self, other):149 if self._pending_removals:150 self._commit_removals()151 if self is other:152 self.data.clear()153 else:154 self.data.difference_update(ref(item) for item in other)155 def __isub__(self, other):156 if self._pending_removals:157 self._commit_removals()158 if self is other:159 self.data.clear()160 else:161 self.data.difference_update(ref(item) for item in other)162 return self163164 def intersection(self, other):165 return self._apply(other, self.data.intersection)166 __and__ = intersection167168 def intersection_update(self, other):169 if self._pending_removals:170 self._commit_removals()171 self.data.intersection_update(ref(item) for item in other)172 def __iand__(self, other):173 if self._pending_removals:174 self._commit_removals()175 self.data.intersection_update(ref(item) for item in other)176 return self177178 def issubset(self, other):179 return self.data.issubset(ref(item) for item in other)180 __lt__ = issubset181182 def __le__(self, other):183 return self.data <= set(ref(item) for item in other)184185 def issuperset(self, other):186 return self.data.issuperset(ref(item) for item in other)187 __gt__ = issuperset188189 def __ge__(self, other):190 return self.data >= set(ref(item) for item in other)191192 def __eq__(self, other):193 if not isinstance(other, self.__class__):194 return NotImplemented195 return self.data == set(ref(item) for item in other)196197 def symmetric_difference(self, other):198 return self._apply(other, self.data.symmetric_difference)199 __xor__ = symmetric_difference200201 def symmetric_difference_update(self, other):202 if self._pending_removals:203 self._commit_removals()204 if self is other:205 self.data.clear()206 else:207 self.data.symmetric_difference_update(ref(item) for item in other)208 def __ixor__(self, other):209 if self._pending_removals:210 self._commit_removals()211 if self is other:212 self.data.clear()213 else:214 self.data.symmetric_difference_update(ref(item) for item in other)215 return self216217 def union(self, other):218 return self._apply(other, self.data.union)219 __or__ = union220221 def isdisjoint(self, other):222 return len(self.intersection(other)) == 0223224225# Instance of old-style class226class _C: pass227_InstanceType = type(_C())228229230def abstractmethod(funcobj):231 """A decorator indicating abstract methods.232233 Requires that the metaclass is ABCMeta or derived from it. A234 class that has a metaclass derived from ABCMeta cannot be235 instantiated unless all of its abstract methods are overridden.236 The abstract methods can be called using any of the normal237 'super' call mechanisms.238239 Usage:240241 class C:242 __metaclass__ = ABCMeta243 @abstractmethod244 def my_abstract_method(self, ...):245 ...246 """247 funcobj.__isabstractmethod__ = True248 return funcobj249250251class abstractproperty(property):252 """A decorator indicating abstract properties.253254 Requires that the metaclass is ABCMeta or derived from it. A255 class that has a metaclass derived from ABCMeta cannot be256 instantiated unless all of its abstract properties are overridden.257 The abstract properties can be called using any of the normal258 'super' call mechanisms.259260 Usage:261262 class C:263 __metaclass__ = ABCMeta264 @abstractproperty265 def my_abstract_property(self):266 ...267268 This defines a read-only property; you can also define a read-write269 abstract property using the 'long' form of property declaration:270271 class C:272 __metaclass__ = ABCMeta273 def getx(self): ...274 def setx(self, value): ...275 x = abstractproperty(getx, setx)276 """277 __isabstractmethod__ = True278279280class ABCMeta(type):281282 """Metaclass for defining Abstract Base Classes (ABCs).283284 Use this metaclass to create an ABC. An ABC can be subclassed285 directly, and then acts as a mix-in class. You can also register286 unrelated concrete classes (even built-in classes) and unrelated287 ABCs as 'virtual subclasses' -- these and their descendants will288 be considered subclasses of the registering ABC by the built-in289 issubclass() function, but the registering ABC won't show up in290 their MRO (Method Resolution Order) nor will method291 implementations defined by the registering ABC be callable (not292 even via super()).293294 """295296 # A global counter that is incremented each time a class is297 # registered as a virtual subclass of anything. It forces the298 # negative cache to be cleared before its next use.299 _abc_invalidation_counter = 0300301 def __new__(mcls, name, bases, namespace):302 cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)303 # Compute set of abstract method names304 abstracts = set(name305 for name, value in namespace.items()306 if getattr(value, "__isabstractmethod__", False))307 for base in bases:308 for name in getattr(base, "__abstractmethods__", set()):309 value = getattr(cls, name, None)310 if getattr(value, "__isabstractmethod__", False):311 abstracts.add(name)312 cls.__abstractmethods__ = frozenset(abstracts)313 # Set up inheritance registry314 cls._abc_registry = WeakSet()315 cls._abc_cache = WeakSet()316 cls._abc_negative_cache = WeakSet()317 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter318 return cls319320 def register(cls, subclass):321 """Register a virtual subclass of an ABC."""322 if not isinstance(subclass, (type, types.ClassType)):323 raise TypeError("Can only register classes")324 if issubclass(subclass, cls):325 return # Already a subclass326 # Subtle: test for cycles *after* testing for "already a subclass";327 # this means we allow X.register(X) and interpret it as a no-op.328 if issubclass(cls, subclass):329 # This would create a cycle, which is bad for the algorithm below330 raise RuntimeError("Refusing to create an inheritance cycle")331 cls._abc_registry.add(subclass)332 ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache333334 def _dump_registry(cls, file=None):335 """Debug helper to print the ABC registry."""336 print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)337 print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter338 for name in sorted(cls.__dict__.keys()):339 if name.startswith("_abc_"):340 value = getattr(cls, name)341 print >> file, "%s: %r" % (name, value)342343 def __instancecheck__(cls, instance):344 """Override for isinstance(instance, cls)."""345 # Inline the cache checking when it's simple.346 subclass = getattr(instance, '__class__', None)347 if subclass is not None and subclass in cls._abc_cache:348 return True349 subtype = type(instance)350 # Old-style instances351 if subtype is _InstanceType:352 subtype = subclass353 if subtype is subclass or subclass is None:354 if (cls._abc_negative_cache_version ==355 ABCMeta._abc_invalidation_counter and356 subtype in cls._abc_negative_cache):357 return False358 # Fall back to the subclass check.359 return cls.__subclasscheck__(subtype)360 return (cls.__subclasscheck__(subclass) or361 cls.__subclasscheck__(subtype))362363 def __subclasscheck__(cls, subclass):364 """Override for issubclass(subclass, cls)."""365 # Check cache366 if subclass in cls._abc_cache:367 return True368 # Check negative cache; may have to invalidate369 if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:370 # Invalidate the negative cache371 cls._abc_negative_cache = WeakSet()372 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter373 elif subclass in cls._abc_negative_cache:374 return False375 # Check the subclass hook376 ok = cls.__subclasshook__(subclass)377 if ok is not NotImplemented:378 assert isinstance(ok, bool)379 if ok:380 cls._abc_cache.add(subclass)381 else:382 cls._abc_negative_cache.add(subclass)383 return ok384 # Check if it's a direct subclass385 if cls in getattr(subclass, '__mro__', ()):386 cls._abc_cache.add(subclass)387 return True388 # Check if it's a subclass of a registered class (recursive)389 for rcls in cls._abc_registry:390 if issubclass(subclass, rcls):391 cls._abc_cache.add(subclass)392 return True393 # Check if it's a subclass of a subclass (recursive)394 for scls in cls.__subclasses__():395 if issubclass(subclass, scls):396 cls._abc_cache.add(subclass)397 return True398 # No dice; update negative cache399 cls._abc_negative_cache.add(subclass)400 return False401402403404405406407408409import sys410411### ONE-TRICK PONIES ###412413def _hasattr(C, attr):414 try:415 return any(attr in B.__dict__ for B in C.__mro__)416 except AttributeError:417 # Old-style class418 return hasattr(C, attr)419420421class Hashable:422 __metaclass__ = ABCMeta423424 @abstractmethod425 def __hash__(self):426 return 0427428 @classmethod429 def __subclasshook__(cls, C):430 if cls is Hashable:431 try:432 for B in C.__mro__:433 if "__hash__" in B.__dict__:434 if B.__dict__["__hash__"]:435 return True436 break437 except AttributeError:438 # Old-style class439 if getattr(C, "__hash__", None):440 return True441 return NotImplemented442443444class Iterable:445 __metaclass__ = ABCMeta446447 @abstractmethod448 def __iter__(self):449 while False:450 yield None451452 @classmethod453 def __subclasshook__(cls, C):454 if cls is Iterable:455 if _hasattr(C, "__iter__"):456 return True457 return NotImplemented458459Iterable.register(str)460461462class Iterator(Iterable):463464 @abstractmethod465 def next(self):466 raise StopIteration467468 def __iter__(self):469 return self470471 @classmethod472 def __subclasshook__(cls, C):473 if cls is Iterator:474 if _hasattr(C, "next") and _hasattr(C, "__iter__"):475 return True476 return NotImplemented477478479class Sized:480 __metaclass__ = ABCMeta481482 @abstractmethod483 def __len__(self):484 return 0485486 @classmethod487 def __subclasshook__(cls, C):488 if cls is Sized:489 if _hasattr(C, "__len__"):490 return True491 return NotImplemented492493494class Container:495 __metaclass__ = ABCMeta496497 @abstractmethod498 def __contains__(self, x):499 return False500501 @classmethod502 def __subclasshook__(cls, C):503 if cls is Container:504 if _hasattr(C, "__contains__"):505 return True506 return NotImplemented507508509class Callable:510 __metaclass__ = ABCMeta511512 @abstractmethod513 def __call__(self, *args, **kwds):514 return False515516 @classmethod517 def __subclasshook__(cls, C):518 if cls is Callable:519 if _hasattr(C, "__call__"):520 return True521 return NotImplemented522523524### SETS ###525526527class Set(Sized, Iterable, Container):528 """A set is a finite, iterable container.529530 This class provides concrete generic implementations of all531 methods except for __contains__, __iter__ and __len__.532533 To override the comparisons (presumably for speed, as the534 semantics are fixed), all you have to do is redefine __le__ and535 then the other operations will automatically follow suit.536 """537538 def __le__(self, other):539 if not isinstance(other, Set):540 return NotImplemented541 if len(self) > len(other):542 return False543 for elem in self:544 if elem not in other:545 return False546 return True547548 def __lt__(self, other):549 if not isinstance(other, Set):550 return NotImplemented551 return len(self) < len(other) and self.__le__(other)552553 def __gt__(self, other):554 if not isinstance(other, Set):555 return NotImplemented556 return other < self557558 def __ge__(self, other):559 if not isinstance(other, Set):560 return NotImplemented561 return other <= self562563 def __eq__(self, other):564 if not isinstance(other, Set):565 return NotImplemented566 return len(self) == len(other) and self.__le__(other)567568 def __ne__(self, other):569 return not (self == other)570571 @classmethod572 def _from_iterable(cls, it):573 '''Construct an instance of the class from any iterable input.574575 Must override this method if the class constructor signature576 does not accept an iterable for an input.577 '''578 return cls(it)579580 def __and__(self, other):581 if not isinstance(other, Iterable):582 return NotImplemented583 return self._from_iterable(value for value in other if value in self)584585 def isdisjoint(self, other):586 for value in other:587 if value in self:588 return False589 return True590591 def __or__(self, other):592 if not isinstance(other, Iterable):593 return NotImplemented594 chain = (e for s in (self, other) for e in s)595 return self._from_iterable(chain)596597 def __sub__(self, other):598 if not isinstance(other, Set):599 if not isinstance(other, Iterable):600 return NotImplemented601 other = self._from_iterable(other)602 return self._from_iterable(value for value in self603 if value not in other)604605 def __xor__(self, other):606 if not isinstance(other, Set):607 if not isinstance(other, Iterable):608 return NotImplemented609 other = self._from_iterable(other)610 return (self - other) | (other - self)611612 # Sets are not hashable by default, but subclasses can change this613 __hash__ = None614615 def _hash(self):616 """Compute the hash value of a set.617618 Note that we don't define __hash__: not all sets are hashable.619 But if you define a hashable set type, its __hash__ should620 call this function.621622 This must be compatible __eq__.623624 All sets ought to compare equal if they contain the same625 elements, regardless of how they are implemented, and626 regardless of the order of the elements; so there's not much627 freedom for __eq__ or __hash__. We match the algorithm used628 by the built-in frozenset type.629 """630 MAX = sys.maxint631 MASK = 2 * MAX + 1632 n = len(self)633 h = 1927868237 * (n + 1)634 h &= MASK635 for x in self:636 hx = hash(x)637 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167638 h &= MASK639 h = h * 69069 + 907133923640 h &= MASK641 if h > MAX:642 h -= MASK + 1643 if h == -1:644 h = 590923713645 return h646647Set.register(frozenset)648649650class MutableSet(Set):651652 @abstractmethod653 def add(self, value):654 """Add an element."""655 raise NotImplementedError656657 @abstractmethod658 def discard(self, value):659 """Remove an element. Do not raise an exception if absent."""660 raise NotImplementedError661662 def remove(self, value):663 """Remove an element. If not a member, raise a KeyError."""664 if value not in self:665 raise KeyError(value)666 self.discard(value)667668 def pop(self):669 """Return the popped value. Raise KeyError if empty."""670 it = iter(self)671 try:672 value = next(it)673 except StopIteration:674 raise KeyError675 self.discard(value)676 return value677678 def clear(self):679 """This is slow (creates N new iterators!) but effective."""680 try:681 while True:682 self.pop()683 except KeyError:684 pass685686 def __ior__(self, it):687 for value in it:688 self.add(value)689 return self690691 def __iand__(self, it):692 for value in (self - it):693 self.discard(value)694 return self695696 def __ixor__(self, it):697 if it is self:698 self.clear()699 else:700 if not isinstance(it, Set):701 it = self._from_iterable(it)702 for value in it:703 if value in self:704 self.discard(value)705 else:706 self.add(value)707 return self708709 def __isub__(self, it):710 if it is self:711 self.clear()712 else:713 for value in it:714 self.discard(value)715 return self716717MutableSet.register(set)718719720### MAPPINGS ###721722723class Mapping(Sized, Iterable, Container):724725 @abstractmethod726 def __getitem__(self, key):727 raise KeyError728729 def get(self, key, default=None):730 try:731 return self[key]732 except KeyError:733 return default734735 def __contains__(self, key):736 try:737 self[key]738 except KeyError:739 return False740 else:741 return True742743 def iterkeys(self):744 return iter(self)745746 def itervalues(self):747 for key in self:748 yield self[key]749750 def iteritems(self):751 for key in self:752 yield (key, self[key])753754 def keys(self):755 return list(self)756757 def items(self):758 return [(key, self[key]) for key in self]759760 def values(self):761 return [self[key] for key in self]762763 # Mappings are not hashable by default, but subclasses can change this764 __hash__ = None765766 def __eq__(self, other):767 if not isinstance(other, Mapping):768 return NotImplemented769 return dict(self.items()) == dict(other.items())770771 def __ne__(self, other):772 return not (self == other)773774class MappingView(Sized):775776 def __init__(self, mapping):777 self._mapping = mapping778779 def __len__(self):780 return len(self._mapping)781782 def __repr__(self):783 return '{0.__class__.__name__}({0._mapping!r})'.format(self)784785786class KeysView(MappingView, Set):787788 @classmethod789 def _from_iterable(self, it):790 return set(it)791792 def __contains__(self, key):793 return key in self._mapping794795 def __iter__(self):796 for key in self._mapping:797 yield key798799800class ItemsView(MappingView, Set):801802 @classmethod803 def _from_iterable(self, it):804 return set(it)805806 def __contains__(self, item):807 key, value = item808 try:809 v = self._mapping[key]810 except KeyError:811 return False812 else:813 return v == value814815 def __iter__(self):816 for key in self._mapping:817 yield (key, self._mapping[key])818819820class ValuesView(MappingView):821822 def __contains__(self, value):823 for key in self._mapping:824 if value == self._mapping[key]:825 return True826 return False827828 def __iter__(self):829 for key in self._mapping:830 yield self._mapping[key]831832833class MutableMapping(Mapping):834835 @abstractmethod836 def __setitem__(self, key, value):837 raise KeyError838839 @abstractmethod840 def __delitem__(self, key):841 raise KeyError842843 __marker = object()844845 def pop(self, key, default=__marker):846 try:847 value = self[key]848 except KeyError:849 if default is self.__marker:850 raise851 return default852 else:853 del self[key]854 return value855856 def popitem(self):857 try:858 key = next(iter(self))859 except StopIteration:860 raise KeyError861 value = self[key]862 del self[key]863 return key, value864865 def clear(self):866 try:867 while True:868 self.popitem()869 except KeyError:870 pass871872 def update(*args, **kwds):873 if len(args) > 2:874 raise TypeError("update() takes at most 2 positional "875 "arguments ({} given)".format(len(args)))876 elif not args:877 raise TypeError("update() takes at least 1 argument (0 given)")878 self = args[0]879 other = args[1] if len(args) >= 2 else ()880881 if isinstance(other, Mapping):882 for key in other:883 self[key] = other[key]884 elif hasattr(other, "keys"):885 for key in other.keys():886 self[key] = other[key]887 else:888 for key, value in other:889 self[key] = value890 for key, value in kwds.items():891 self[key] = value892893 def setdefault(self, key, default=None):894 try:895 return self[key]896 except KeyError:897 self[key] = default898 return default899900MutableMapping.register(dict)901902903### SEQUENCES ###904905906class Sequence(Sized, Iterable, Container):907 """All the operations on a read-only sequence.908909 Concrete subclasses must override __new__ or __init__,910 __getitem__, and __len__.911 """912913 @abstractmethod914 def __getitem__(self, index):915 raise IndexError916917 def __iter__(self):918 i = 0919 try:920 while True:921 v = self[i]922 yield v923 i += 1924 except IndexError:925 return926927 def __contains__(self, value):928 for v in self:929 if v == value:930 return True931 return False932933 def __reversed__(self):934 for i in reversed(range(len(self))):935 yield self[i]936937 def index(self, value):938 for i, v in enumerate(self):939 if v == value:940 return i941 raise ValueError942943 def count(self, value):944 return sum(1 for v in self if v == value)945946Sequence.register(tuple)947Sequence.register(basestring)948Sequence.register(buffer)949Sequence.register(xrange)950951952class MutableSequence(Sequence):953954 @abstractmethod955 def __setitem__(self, index, value):956 raise IndexError957958 @abstractmethod959 def __delitem__(self, index):960 raise IndexError961962 @abstractmethod963 def insert(self, index, value):964 raise IndexError965966 def append(self, value):967 self.insert(len(self), value)968969 def reverse(self):970 n = len(self)971 for i in range(n//2):972 self[i], self[n-i-1] = self[n-i-1], self[i]973974 def extend(self, values):975 for v in values:976 self.append(v)977978 def pop(self, index=-1):979 v = self[index]980 del self[index]981 return v982983 def remove(self, value):984 del self[self.index(value)]985986 def __iadd__(self, values):987 self.extend(values)988 return self989990MutableSequence.register(list)991
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+139 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.php678from collections import deque9from threading import RLock1011try:12 from collections import MutableMapping13except ImportError:14 from .__collections import MutableMapping1516__all__ = ['RecentlyUsedContainer']171819class AccessEntry(object):20 __slots__ = ('key', 'is_valid')2122 def __init__(self, key, is_valid=True):23 self.key = key24 self.is_valid = is_valid252627class RecentlyUsedContainer(MutableMapping):28 """29 Provides a dict-like that maintains up to ``maxsize`` keys while throwing30 away the least-recently-used keys beyond ``maxsize``.31 """3233 # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we34 # will attempt to cleanup the invalidated entries in the access_log35 # datastructure during the next 'get' operation.36 CLEANUP_FACTOR = 103738 def __init__(self, maxsize=10):39 self._maxsize = maxsize4041 self._container = {}4243 # We use a deque to to store our keys ordered by the last access.44 self.access_log = deque()45 self.access_log_lock = RLock()4647 # We look up the access log entry by the key to invalidate it so we can48 # insert a new authorative entry at the head without having to dig and49 # find the old entry for removal immediately.50 self.access_lookup = {}5152 # Trigger a heap cleanup when we get past this size53 self.access_log_limit = maxsize * self.CLEANUP_FACTOR5455 def _invalidate_entry(self, key):56 "If exists: Invalidate old entry and return it."57 old_entry = self.access_lookup.get(key)58 if old_entry:59 old_entry.is_valid = False6061 return old_entry6263 def _push_entry(self, key):64 "Push entry onto our access log, invalidate the old entry if exists."65 self._invalidate_entry(key)6667 new_entry = AccessEntry(key)68 self.access_lookup[key] = new_entry6970 self.access_log_lock.acquire()71 self.access_log.appendleft(new_entry)72 self.access_log_lock.release()7374 def _prune_entries(self, num):75 "Pop entries from our access log until we popped ``num`` valid ones."76 while num > 0:77 self.access_log_lock.acquire()78 p = self.access_log.pop()79 self.access_log_lock.release()8081 if not p.is_valid:82 continue # Invalidated entry, skip8384 self._container.pop(p.key, None)85 self.access_lookup.pop(p.key, None)86 num -= 18788 def _prune_invalidated_entries(self):89 "Rebuild our access_log without the invalidated entries."90 self.access_log_lock.acquire()91 self.access_log = deque(e for e in self.access_log if e.is_valid)92 self.access_log_lock.release()9394 def _get_ordered_access_keys(self):95 "Return ordered access keys for inspection. Used for testing."96 self.access_log_lock.acquire()97 r = [e.key for e in self.access_log if e.is_valid]98 self.access_log_lock.release()99100 return r101102 def __getitem__(self, key):103 item = self._container.get(key)104105 if not item:106 raise KeyError(key)107108 # Insert new entry with new high priority, also implicitly invalidates109 # the old entry.110 self._push_entry(key)111112 if len(self.access_log) > self.access_log_limit:113 # Heap is getting too big, try to clean up any tailing invalidated114 # entries.115 self._prune_invalidated_entries()116117 return item118119 def __setitem__(self, key, item):120 # Add item to our container and access log121 self._container[key] = item122 self._push_entry(key)123124 # Discard invalid and excess entries125 self._prune_entries(len(self._container) - self._maxsize)126127 def __delitem__(self, key):128 self._invalidate_entry(key)129 del self._container[key]130 del self.access_lookup[key]131132 def __len__(self):133 return self._container.__len__()134135 def __iter__(self):136 return self._container.__iter__()137138 def __contains__(self, key):139 return self._container.__contains__(key)
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 %s 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+194 added-126 removed
3 unmodified lines
4"""5requests.models6~~~~~~~~~~~~~~~78This module contains the primary objects that power Requests.9"""1011import urllib11import urllib212import socket12import zlib1314from Cookie import SimpleCookie15from urlparse import urlparse, urlunparse, urljoin16from datetime import datetime1718from .auth import dispatch as auth_dispatch19from .hooks import dispatch_hook20from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers21from .status_codes import codes24from .exceptions import Timeout, URLRequired, TooManyRedirects25from .monkeys import Request as _Request26from .monkeys import HTTPRedirectHandler22from .packages.urllib3.exceptions import MaxRetryError23from .packages.urllib3.exceptions import SSLError as _SSLError24from .packages.urllib3.exceptions import HTTPError as _HTTPError25from .packages.urllib3 import connectionpool, poolmanager26from .packages.urllib3.filepost import encode_multipart_formdata27from .exceptions import (28 Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)29from .utils import (28 dict_from_cookiejar, get_unicode_from_response,29 stream_decode_response_unicode, decode_gzip, stream_decode_gzip)30 get_unicode_from_response, stream_decode_response_unicode,31 decode_gzip, stream_decode_gzip)3233343536REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)373839
15 unmodified lines
55 redirect=False,56 allow_redirects=False,57 proxies=None,58 hooks=None,55 config=None):59 config=None,60 _poolmanager=None):6162 #: Float describes the timeout of the request.63 # (Use socket.setdefaulttimeout() as fallback)64 self.timeout = timeout
1 unmodified line
66 #: Request URL.67 self.url = url6869 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.65 self.headers = headers70 self.headers = dict(headers or [])7172 #: Dictionary of files to multipart upload (``{filename: content}``).73 self.files = files74
6 unmodified lines
8182 #: Dictionary or byte of querystring data to attach to the83 #: :class:`Request <Request>`.84 self.params = None85 self.params = dict(params or [])8687 #: True if :class:`Request <Request>` is part of a redirect chain (disables history88 #: and HTTPError storage).89 self.redirect = redirect
1 unmodified line
91 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)92 self.allow_redirects = allow_redirects9394 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})89 self.proxies = proxies95 self.proxies = dict(proxies or [])9697 self.data, self._enc_data = self._encode_params(data)98 self.params, self._enc_params = self._encode_params(params)99
5 unmodified lines
105 self._auth = auth106 self.auth = auth_dispatch(auth)107108 #: CookieJar to attach to :class:`Request <Request>`.103 self.cookies = cookies109 self.cookies = dict(cookies or [])110111 #: Dictionary of configurations for this request.106 self.config = config112 self.config = dict(config or [])113114 #: True if Request has been sent.115 self.sent = False116117 #: Event-handling hooks.118 self.hooks = hooks119120 #: Session.121 self.session = None122123 if headers:124 headers = CaseInsensitiveDict(self.headers)125 else:126 headers = CaseInsensitiveDict()
2 unmodified lines
129 if k not in headers:130 headers[k] = v131132 self.headers = headers133 self._poolmanager = _poolmanager134135 # Pre-request hook.136 r = dispatch_hook('pre_request', hooks, self)137 self.__dict__.update(r.__dict__)
2 unmodified lines
140 def __repr__(self):141 return '<Request [%s]>' % (self.method)142143134 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.open165166144 def _build_response(self, resp, is_error=False):145 """Build internal :class:`Response <Response>` object146 from given response.147 """
1 unmodified line
149150 def build(resp):151152 response = Response()153154 # Pass settings over.155 response.config = self.config177 response.status_code = getattr(resp, 'code', None)156179 try:180 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))181 response.raw = resp157 if resp:158183 if self.cookies:184 response.cookies = dict_from_cookiejar(self.cookies)159 # Fallback to None if there's no staus_code, for whatever reason.160 response.status_code = getattr(resp, 'status', None)161162 # Make headers case-insensitive.163 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))164187 except AttributeError:188 pass165 # Start off with our local cookies.166 cookies = self.cookies or dict()167168 # Add new cookies from the server.169 if 'set-cookie' in response.headers:170 cookie_header = response.headers['set-cookie']171172 c = SimpleCookie()173 c.load(cookie_header)174175 for k,v in c.items():176 cookies.update({k: v.value})177178 # Save cookies in Response.179 response.cookies = cookies180181 # Save original resopnse for later.182 response.raw = resp183184 if is_error:185 response.error = resp186193 response.url = getattr(resp, 'url', None)187 response.url = self._build_url()188189 return response190191192 history = []193194 r = build(resp)195 cookies = self.cookies196 self.cookies.update(r.cookies)197198 if r.status_code in REDIRECT_STATI and not self.redirect:199200 while (201 ('location' in r.headers) and202 ((r.status_code is codes.see_other) or (self.allow_redirects))203 ):204209 r.raw.close()210205 if not len(history) < self.config.get('max_redirects'):206 raise TooManyRedirects()207208 history.append(r)
15 unmodified lines
224 method = 'GET'225 else:226 method = self.method227228 # Remove the cookie headers that were sent.229 headers = self.headers230 try:231 del headers['Cookie']232 except KeyError:233 pass234235 request = Request(236 url=url,236 headers=self.headers,237 headers=headers,238 files=self.files,239 method=method,239 # data=self.data,240 # params=self.params,240 params=self.session.params,241 auth=self._auth,242 cookies=self.cookies,242 cookies=cookies,243 redirect=True,244 config=self.config244 config=self.config,245 _poolmanager=self._poolmanager246 )247248 request.send()249 cookies.update(request.response.cookies)250 r = request.response251 self.cookies.update(r.cookies)252253 r.history = history254255 self.response = r256 self.response.request = self257 self.response.cookies.update(self.cookies)258259260 @staticmethod261 def _encode_params(data):
6 unmodified lines
268 Otherwise, assumes the data is already encoded appropriately, and269 returns it twice.270 """271272 if hasattr(data, '__iter__'):273 data = dict(data)274275 if hasattr(data, 'items'):276 result = []277 for k, vs in data.items():278 for v in isinstance(vs, list) and vs or [vs]:
6 unmodified lines
285286 def _build_url(self):287 """Build the actual URL to use."""288289 if not self.url:290 raise URLRequired()291292 # Support for unicode domain names and paths.293 scheme, netloc, path, params, query, fragment = urlparse(self.url)294295 if not scheme:296 raise ValueError()297298 netloc = netloc.encode('idna')299300 if isinstance(path, unicode):301 path = path.encode('utf-8')302303 path = urllib.quote(urllib.unquote(path))304 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))305306 if self._enc_params:
4 unmodified lines
311 else:312 return self.url313314298 def send(self, anyway=False):315 def send(self, anyway=False, prefetch=False):316 """Sends the request. Returns True of successful, false if not.317 If there was an HTTPError during transmission,318 self.response.status_code will contain the HTTPError code.319
2 unmodified lines
322 :param anyway: If True, request will be sent, even if it has323 already been sent.324 """325309 # Some people...310 if not self.url:311 raise URLRequired312326 # Logging327 if self.config.get('verbose'):328 self.config.get('verbose').write('%s %s %s\n' % (329 datetime.now().isoformat(), self.method, self.url
1 unmodified line
331332 # Build the URL333 url = self._build_url()334322 # Attach uploaded files.335 # Nottin' on you.336 body = None337 content_type = None338339 # Multi-part file uploads.340 if self.files:324 register_openers()341 if not isinstance(self.data, basestring):342326 # Add form-data to the multipart.343 try:344 fields = self.data.copy()345 except AttributeError:346 fields = dict(self.data)347348 for (k, v) in self.files.items():349 fields.update({k: (k, v.read())})350 (body, content_type) = encode_multipart_formdata(fields)351 else:352 pass353 # TODO: Conflict?354 else:355 if self.data:328 self.files.update(self.data)356330 data, headers = multipart_encode(self.files)357 body = self._enc_data358 if isinstance(self.data, basestring):359 content_type = None360 else:361 content_type = 'application/x-www-form-urlencoded'362332 else:333 data = self._enc_data334 headers = {}363 # Add content-type if it wasn't explicitly provided.364 if (content_type) and (not 'content-type' in self.headers):365 self.headers['Content-Type'] = content_type366367368 if self.auth:369 auth_func, auth_args = self.auth370371 # Allow auth to make its changes.372 r = auth_func(self, *auth_args)373374 # Update self to reflect the auth changes.375 self.__dict__.update(r.__dict__)376343 # Build the Urllib2 Request.344 req = _Request(url, data=data, headers=headers, method=self.method)377 _p = urlparse(url)378 proxy = self.proxies.get(_p.scheme)379346 # Add the headers to the request.347 if self.headers:348 for k,v in self.headers.iteritems():349 req.add_header(k, v)380 if proxy:381 conn = poolmanager.proxy_from_url(url)382 else:383 # Check to see if keep_alive is allowed.384 if self.config.get('keep_alive'):385 conn = self._poolmanager.connection_from_url(url)386 else:387 conn = connectionpool.connection_from_url(url)388389 if not self.sent or anyway:390353 try:354 opener = self._get_opener()355 try:391 if self.cookies:392357 resp = opener(req, timeout=self.timeout)393 # Skip if 'cookie' header is explicitly set.394 if 'cookie' not in self.headers:395359 except TypeError, err:360 # timeout argument is new since Python v2.6361 if not 'timeout' in str(err):362 raise396 # Simple cookie with our dict.397 c = SimpleCookie()398 for (k, v) in self.cookies.items():399 c[k] = v400364 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)401 # Turn it into a header.402 cookie_header = c.output(header='').strip()403369 resp = opener(req)404 # Attach Cookie header to request.405 self.headers['Cookie'] = cookie_header406371 if self.config.get('timeout_fallback'):372 # restore global timeout373 socket.setdefaulttimeout(old_timeout)407 try:408 # Send the request.409375 if self.cookies is not None:376 self.cookies.extract_cookies(resp, req)410 r = conn.urlopen(411 method=self.method,412 url=url,413 body=body,414 headers=self.headers,415 redirect=False,416 assert_same_host=False,417 preload_content=prefetch,418 decode_content=False,419 retries=self.config.get('max_retries', 0),420 timeout=self.timeout,421 )422378 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)423385 self._build_response(why, is_error=True)424 except MaxRetryError, e:425 if not self.config.get('safe_mode', False):426 raise ConnectionError(e)427 else:428 r = None429387 else:388 self._build_response(resp)389 self.response.ok = True430 except (_SSLError, _HTTPError), e:431 if not self.config.get('safe_mode', False):432 raise Timeout('Request timed out.')433434 self._build_response(r)435392 self.sent = self.response.ok436 # Response manipulation hook.437 self.response = dispatch_hook('response', self.hooks, self.response)438394 # Response manipulation hook.395 self.response = dispatch_hook('response', self.hooks, self.response)439 # Post-request hook.440 r = dispatch_hook('post_request', self.hooks, self)441 self.__dict__.update(r.__dict__)442397 # Post-request hook.398 r = dispatch_hook('post_request', self.hooks, self)399 self.__dict__.update(r.__dict__)443 # If prefetch is True, mark content as consumed.444 if prefetch:445 self.response._content_consumed = True446401 return self.sent447 return self.sent448449450class Response(object):451 """The core :class:`Response <Response>` object. All
20 unmodified lines
472473 #: Final URL location of Response.474 self.url = None475430 #: True if no :attr:`error` occurred.431 self.ok = False432476 #: Resulting :class:`HTTPError` of request, if one occurred.477 self.error = None478479 #: A list of :class:`Response <Response>` objects from
4 unmodified lines
484 #: The :class:`Request <Request>` that created the Response.485 self.request = None486487 #: A dictionary of Cookies the server sent back.445 self.cookies = None488 self.cookies = {}489490 #: Dictionary of configurations for this request.448 self.config = None491 self.config = {}492493494 def __repr__(self):495 return '<Response [%s]>' % (self.status_code)496454497 def __nonzero__(self):498 """Returns true if :attr:`status_code` is 'OK'."""499 return self.ok500458 return not self.error501 @property502 def ok(self):503 try:504 self.raise_for_status()505 except HTTPError:506 return False507 return True508509510 def iter_content(self, chunk_size=10 * 1024, decode_unicode=None):511 """Iterates over the response data. This avoids reading the content512 at once into memory for large responses. The chunk size is the number513 of bytes it should read into memory. This is not necessarily the514 length of each item returned as decoding can take place.515 """516 if self._content_consumed:467 raise RuntimeError('The content for this response was '468 'already consumed')517 raise RuntimeError(518 'The content for this response was already consumed'519 )520521 def generate():522 while 1:523 chunk = self.raw.read(chunk_size)524 if not chunk:525 break526 yield chunk527 self._content_consumed = True528529 gen = generate()530531 if 'gzip' in self.headers.get('content-encoding', ''):532 gen = stream_decode_gzip(gen)533534 if decode_unicode is None:535 decode_unicode = self.config.get('decode_unicode')536537 if decode_unicode:538 gen = stream_decode_response_unicode(gen, self)539540 return gen541542543 @property544 def content(self):545 """Content of the response, in bytes or unicode546 (if available).
29 unmodified lines
576577578 def raise_for_status(self):579 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""580581 if self.error:582 raise self.error583584 if (self.status_code >= 300) and (self.status_code < 400):585 raise HTTPError('%s Redirection' % self.status_code)586587 elif (self.status_code >= 400) and (self.status_code < 500):588 raise HTTPError('%s Client Error' % self.status_code)589590 elif (self.status_code >= 500) and (self.status_code < 600):591 raise HTTPError('%s Server Error' % self.status_code)592593
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:AUTHORS+4 added-1 removed
47 unmodified lines
48- Fredrik Möllerstrand49- Daniel Hengeveld50- Dan Head51- Bruno Renié52- David Fischer52- David Fischer53- Joseph McCullough54- Juergen Brendel55- Juan Riaza
modified:HISTORY.rst+14 added
1History2-------3450.8.0 (2011-11-09)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 throttling17180.7.6 (2011-11-07)19++++++++++++++++++2021* 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