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
Provenance
- Commit
b401282- Tree
7f00dc5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
72943d0- Parent 2
14a7988
37 files changed+3160 added−1021 removed
modified:docs/_themes/kr/static/flasky.css_t+91 added-1 removed
385 unmodified lines386 background: #EEE;387 }388 389 390-@media screen and (max-width: 600px) {390+@media screen and (max-width: 870px) {391 392 div.sphinxsidebar {393 display: none;394 }40 unmodified lines435 .github {436 display: none;437 }438 439+440+441 }442 443 444+445+@media screen and (max-width: 875px) {446+447+ body {448+ margin: 0;449+ padding: 20px 30px;450+ }451+452+ div.documentwrapper {453+ float: none;454+ background: white;455+ }456+457+ 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+ }466+467+ div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,468+ div.sphinxsidebar h3 a {469+ color: white;470+ }471+472+ div.sphinxsidebar a {473+ color: #aaa;474+ }475+476+ div.sphinxsidebar p.logo {477+ display: none;478+ }479+480+ div.document {481+ width: 100%;482+ margin: 0;483+ }484+485+ div.related {486+ display: block;487+ margin: 0;488+ padding: 10px 0 20px 0;489+ }490+491+ div.related ul,492+ div.related ul li {493+ margin: 0;494+ padding: 0;495+ }496+497+ div.footer {498+ display: none;499+ }500+501+ div.bodywrapper {502+ margin: 0;503+ }504+505+ div.body {506+ min-height: 0;507+ padding: 0;508+ }509+510+ .rtd_doc_footer {511+ display: none;512+ }513+514+ .document {515+ width: auto;516+ }517+518+ .footer {519+ width: auto;520+ }521+522+ .footer {523+ width: auto;524+ }525+526+ .github {527+ display: none;528+ }529+}530+531+532 /* scrollbars */533 534 ::-webkit-scrollbar {535 width: 6px;35 unmodified linesdeleted: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- */8-9-body {10- margin: 0;11- padding: 20px 30px;12-}13-14-div.documentwrapper {15- float: none;16- background: white;17-}18-19-div.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-}28-29-div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,30-div.sphinxsidebar h3 a {31- color: white;32-}33-34-div.sphinxsidebar a {35- color: #aaa;36-}37-38-div.sphinxsidebar p.logo {39- display: none;40-}41-42-div.document {43- width: 100%;44- margin: 0;45-}46-47-div.related {48- display: block;49- margin: 0;50- padding: 10px 0 20px 0;51-}52-53-div.related ul,54-div.related ul li {55- margin: 0;56- padding: 0;57-}58-59-div.footer {60- display: none;61-}62-63-div.bodywrapper {64- margin: 0;65-}66-67-div.body {68- min-height: 0;69- padding: 0;70-}71-72-.rtd_doc_footer {73- display: none;74-}75-76-.document {77- width: auto;78-}79-80-.footer {81- width: auto;82-}83-84-.footer {85- width: auto;86-}87-88-.github {89- display: none;90-}modified:docs/_themes/kr/layout.html-2 removed
2 unmodified lines3456787891036 unmodified lines2 unmodified lines {{ super() }} {% if theme_touch_icon %} <link rel="apple-touch-icon" href="{{ pathto('_static/' ~ theme_touch_icon, 1) }}" /> {% endif %} <link media="only screen and (max-device-width: 480px)" href="{{ pathto('_static/small_flask.css', 1) }}" type= "text/css" rel="stylesheet" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">{% endblock %}{%- block relbar2 %}{% endblock %}{%- block footer %}36 unmodified linesmodified:docs/community/faq.rst+1 added-1 removed
71 unmodified lines72 73 Keep-alive Support?74 -------------------75 76-It's on the way.76+Yep!77 78 79 Proxy Support?80 --------------3 unmodified linesmodified:docs/community/out-there.rst+1 added-1 removed
1 Modules2 =======3 4-- `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 linesmodified:docs/user/advanced.rst+58 added-9 removed
8 unmodified lines9 Session Objects10 ---------------11 12 The Session object allows you to persist certain parameters across13-requests. It also establishes a CookieJar and passes it along14-to any requests made from the Session instance.13+requests. It also perstists cookies across all requests made from the14+Session instance.15 16 A session object has all the methods of the main Requests API.17 18 Let's persist some cookies across requests::17 unmodified lines36 # both 'x-test' and 'x-test2' are sent37 c.get('http://httpbin.org/headers', headers={'x-test2': 'true'})38 39 40-.. admonition:: Global Settings40+Any 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.41 42- Certain parameters are best set in the ``config`` dictionary43- (e.g. user agent header).42+.. admonition:: Remove a Value From a Dict Parameter43 44+ 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.45 46+All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.47+48+49+Body Content Workflow50+----------------------51+52+By 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.53+54+Let's walk through it::55+56+ tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'57+ r = requests.get(tarball_url)58+59+The request has been made, but the connection is still open. The response body has not been downloaded yet. ::60+61+ r.content62+63+The content has been downloaded and cached.64+65+You can override this default behavior with the ``prefetch`` parameter::66+67+ r = requests.get(tarball_url, prefetch=True)68+ # Blocks until all of request body has been downloaded.69+70+71+Configuring Requests72+--------------------73+74+Sometimes you may want to configure a request to customize it's behavior. To do75+this, you can pass in a ``config`` dictionary to a request or session. See the :ref:`Configuration API Docs <configurations>` to learn more.76+77+78+Keep-Alive79+----------80+81+Excellent 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!82+83+If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::84+85+ s = requests.session()86+ s.config['keep_alive'] = False87+88+89 Asynchronous Requests90 ----------------------91 49-Requests has first-class support for non-blocking i/o requests, powered92+Requests has first-class support for concurrent requests, powered93 by gevent. This allows you to send a bunch of HTTP requests at the same94 95 First, 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::97 98 from requests import async99 100 The ``async`` module has the exact same api as ``requests``, except it18 unmodified lines119 120 >>> async.map(rs)121 [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]122 123+.. admonition:: Throttling124 125+ The ``map`` function also takes a ``size`` parameter, that specifies the nubmer of connections to make at a time::126+127+ async.map(rs, size=5)128+129+130 Event Hooks131 -----------132 133 Requests has a hook system that you can use to manipulate portions of113 unmodified lines247 by your application, you can turn on verbose logging.248 249 To do so, just configure Requests with a stream to write to::250 202- >>> 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 lines38 39 >>> r.content40 '[{"repository":{"open_issues":0,"url":"https://github.com/...41 42+Requests does its best to decode content from the server. Most unicode charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.43 44+45+Make a POST Request46+-------------------47+48+POST requests are equally simple::49+50+ r = requests.post("http://httpbin.org/post")51+52+53+Typically, you want to send some form-encoded data — much like an HTML form.54+To do this, simply pass a dictionary to the `data` argument. Your dictionary of data will automatically be form-encoded when the request is made::55+56+ >>> 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+ }78+79+There 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.80+81+For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::82+83+ url = 'https://api.github.com/some/endpoint'84+ payload = {'some': 'data'}85+86+ r = requests.post(url, data=json.dumps(payload))87+88+89+Custom Headers90+--------------91+92+If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the93+``headers`` parameter.94+95+For example, we didn't specify our content-type in the previous example::96+97+ url = 'https://api.github.com/some/endpoint'98+ payload = {'some': 'data'}99+ headers = {'content-type': 'application/json'}100+101+ r = requests.post(url, data=json.dumps(payload), headers=headers)102+103+104+POST a Multipart-Encoded File105+-----------------------------106+107+Requests makes it simple to upload Multipart-encoded files::108+109+ >>> url = 'http://httpbin.org/post'110+ >>> files = {'report.xls': open('report.xls', 'rb')}111+112+ >>> 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+ }132+133+134+135 Response Status Codes136 ---------------------137 138 We can check the response status code::6 unmodified lines145 146 >>> r.status_code == requests.codes.ok147 True148 57-If we made a bad request, we can raise it with149+If we made a bad request (non-200 response), we can raise it with150 :class:`Response.raise_for_status()`::151 152 >>> _r = requests.get('http://httpbin.org/status/404')153 >>> _r.status_code59 unmodified lines213 214 >>> print r.cookies215 {'requests-is': 'awesome'}216 125-The underlying CookieJar is also available for more advanced handling::126-127- >>> r.request.cookiejar128- <cookielib.CookieJar>129-217 To send your own cookies to the server, you can use the ``cookies``218 parameter::219 220 >>> url = 'http://httpbin.org/cookies'7 unmodified lines228 Basic Authentication229 --------------------230 231 Most web services require authentication. There many different types of145-authentication, but the most common is called HTTP Basic Auth.232+authentication, but the most common is HTTP Basic Auth.233 147-Making requests with Basic Auth is easy, with Requests::234+Making requests with Basic Auth is extremely simple::235 236 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))237 <Response [200]>238 239 240 Digest Authentication241 ---------------------242 156-Another popular form of protecting web service is Digest Authentication.243+Another popular form of web service protection is Digest Authentication::244 158-Requests supports it!::159-245 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'246 >>> requests.get(url, auth=('digest', 'user', 'pass'))247 <Response [200]>248 249 250+Redirection and History251 -----------------------252 253+Requests will automatically perform location redirection while using impodotent methods.254+255+GitHub redirects all HTTP requests to HTTPS. Let's see what happens::256+257+ >>> r = request.get('http://github.com')258+ >>> r.url259+ 'https://github.com/'260+ >>> r.status_code261+ 200262+ >>> r.history263+ [<Response [301]>]264+265+The :class:`Response.history` list contains a list of the266+:class:`Request` objects that were created in order to complete the request.267+268+If you're using GET, HEAD, or OPTIONS, you can disable redirection269+handling with the ``disable_redirects`` parameter::270+271+ >>> r = request.get('http://github.com')272+ >>> r.status_code273+ 301274+ >>> r.history275+ []276+277+If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::278+279+ >>> r = request.post('http://github.com')280+ >>> r.url281+ 'https://github.com/'282+ >>> r.history283+ [<Response [301]>]284+285+286+Timeouts287+--------288+289+You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::290+291+ >>> 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.295+296+.. admonition:: Note297+298+ ``timeout`` only effects the connection process itself, not the downloading of the respone body.299+300+301+Note302+303+Errors and Exceptions304+---------------------305+306+In the event of a network problem (e.g. DNS failure, refused connection, etc),307+Requests will raise a :class:`ConnectionError` exception.308+309+In the event of the rare invalid HTTP response, Requests will raise310+an :class:`HTTPError` exception.311+312+If a request times out, a :class:`Timeout` exception is raised.313+314+If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.315+316+All exceptions that Requests explicitly raises inherit from317+:class:`requests.exceptions.RequestException`.318+319+-----------------------320+321 Ready for more? Check out the :ref:`advanced <advanced>` section.modified:docs/api.rst+57 added-18 removed
15 unmodified lines16 All of Request's functionality can be accessed by these 7 methods.17 They all return an instance of the :class:`Response <Response>` object.18 19 .. autofunction:: request20+21+---------------------22+23+24+.. autoclass:: Response25+ :inherited-members:26+27+---------------------28+29 .. autofunction:: head30 .. autofunction:: get31 .. autofunction:: post32 .. autofunction:: put33 .. autofunction:: patch34 .. autofunction:: delete35 36 28------------37+-----------------38 39+.. autofunction:: session40 31-.. autoclass:: Response32- :inherited-members:41 42+43+Exceptions44+~~~~~~~~~~45+46+.. module:: requests47+48+.. autoexception:: RequestException49+.. autoexception:: ConnectionError50+.. autoexception:: HTTPError51+.. autoexception:: URLRequired52+.. autoexception:: TooManyRedirects53+54+55+.. _configurations:56+57+Configurations58+--------------59+60+.. automodule:: requests.defaults61+62+63+.. _async:64+65 Async66 -----67 68 .. module:: requests.async17 unmodified lines86 Requests.87 88 .. module:: requests.utils89 90+Status Code Lookup91+~~~~~~~~~~~~~~~~~~92+93+.. autofunction:: requests.codes94+95+::96+97+ >>> requests.codes['temporary_redirect']98+ 30199+100+ >>> requests.codes.teapot101+ 416102+103+ >>> requests.codes['\o/']104+ 416105+106 Cookies107 ~~~~~~~108 109 .. autofunction:: dict_from_cookiejar16 unmodified lines126 These items are an internal component to Requests, and should never be127 seen by the end user (developer). This part of the API documentation128 exists for those who are extending the functionality of Requests.129 83-Exceptions84-~~~~~~~~~~130 86-.. module:: requests87-88-.. autoexception:: HTTPError89-90-.. autoexception:: RequestException91-92-.. autoexception:: AuthenticationError93-.. autoexception:: URLRequired94-.. autoexception:: InvalidMethod95-.. autoexception:: TooManyRedirects96-97-98-131 Classes132 ~~~~~~~133 134+.. autoclass:: requests.Response135+ :inherited-members:136+137 .. autoclass:: requests.Request138 :inherited-members:139 140+.. _sessionapi:141 142+.. autoclass:: requests.Session143+ :inherited-members:144+modified:docs/index.rst+2 added-3 removed
31 unmodified lines32 33 Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,34 **PATCH**, and **DELETE** HTTP requests. You can add headers, form data,35 multipart files, and parameters with simple Python dictionaries, and access the36-response data in the same way. It's powered by :py:class:`urllib2`, but it does37-all the hard work and crazy hacks for you.36+response 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.37 38 Testimonials39 ------------40 41 `The Washington Post <http://www.washingtonpost.com/>`_, `Twitter, Inc <http://twitter.com>`_,42 a U.S. Federal Institution,44-NIH, 43+NIH,44 `Readability <http://readability.com>`_, and45 `Work for Pie <http://workforpie.com>`_46 use Requests internally.47 70 unmodified linesdeleted: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 module21-22-Support for streaming HTTP uploads, and multipart/form-data encoding23-24-```poster.version``` is a 3-tuple of integers representing the version number.25-New releases of poster will always have a version number that compares greater26-than an older version of poster.27-New in version 0.6."""28-29-from __future__ import absolute_import30-31-from . import streaminghttp32-from . import encode33-34-version = (0, 8, 0) # Thanks JP!deleted:requests/packages/poster/encode.py-414 removed
1-"""multipart/form-data encoding module2-3-This module provides functions that faciliate encoding name/value pairs4-as multipart/form-data suitable for a HTTP POST or PUT request.5-6-multipart/form-data is the standard way to upload files over HTTP"""7-8-__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',9- 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',10- 'multipart_encode']11-12-try:13- import uuid14- def gen_boundary():15- """Returns a random string to use as the boundary for a message"""16- return uuid.uuid4().hex17-except 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()23-24-import urllib, re, os, mimetypes25-try:26- from email.header import Header27-except ImportError:28- # Python 2.429- from email.Header import Header30-31-def 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 None36-37- if isinstance(data, unicode):38- data = data.encode("utf-8")39- return urllib.quote_plus(data)40-41-def _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)49-50-class MultipartParam(object):51- """Represents a single parameter in a multipart/form-data request52-53- ``name`` is the name of this parameter.54-55- If ``value`` is set, it must be a string or unicode object to use as the56- data for this parameter.57-58- 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.60-61- If ``filetype`` is set, it is used as the Content-Type for this parameter.62- If unset it defaults to "text/plain; charset=utf8"63-64- If ``filesize`` is set, it specifies the length of the file ``fileobj``65-66- If ``fileobj`` is set, it must be a file-like object that supports67- .read().68-69- Both ``value`` and ``fileobj`` must not be set, doing so will70- raise a ValueError assertion.71-72- 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.77-78- ``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)97-98- self.filesize = filesize99- self.fileobj = fileobj100- self.cb = cb101-102- if self.value is not None and self.fileobj is not None:103- raise ValueError("Only one of value or fileobj may be specified")104-105- 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")116-117- 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)122-123- 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")128-129- @classmethod130- def from_file(cls, paramname, filename):131- """Returns a new MultipartParam object constructed from the local132- file at ``filename``.133-134- ``filesize`` is determined by os.path.getsize(``filename``)135-136- ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]137-138- ``filename`` is set to os.path.basename(``filename``)139- """140-141- 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"))145-146- @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 values151-152- 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()157-158- 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 = None175-176- retval.append(cls(name=name, filename=filename,177- filetype=filetype, fileobj=value))178- else:179- retval.append(cls(name, value))180- return retval181-182- def encode_hdr(self, boundary):183- """Returns the header of the encoding of this parameter"""184- boundary = encode_and_quote(boundary)185-186- headers = ["--%s" % boundary]187-188- 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.name193-194- headers.append("Content-Disposition: %s" % disposition)195-196- if self.filetype:197- filetype = self.filetype198- else:199- filetype = "text/plain; charset=utf-8"200-201- headers.append("Content-Type: %s" % filetype)202-203- headers.append("")204- headers.append("")205-206- return "\r\n".join(headers)207-208- 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.value214-215- if re.search("^--%s$" % re.escape(boundary), value, re.M):216- raise ValueError("boundary found in encoded string")217-218- return "%s%s\r\n" % (self.encode_hdr(boundary), value)219-220- 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)258-259- 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)266-267- return len(self.encode_hdr(boundary)) + 2 + valuesize268-269-def 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."""273-274- return MultipartParam(name, value).encode(boundary)275-276-def 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.280-281- ``boundary`` is the boundary string used throughout a single request to282- separate variables.283-284- ``paramname`` is the name of the variable in this request.285-286- ``filesize`` is the size of the file data.287-288- ``filename`` if specified is the filename to give to this field. This289- field is only useful to the server for determining the original filename.290-291- ``filetype`` if specified is the MIME type of this file.292-293- The actual file data should be sent after this header has been sent.294- """295-296- return MultipartParam(paramname, filesize=filesize, filename=filename,297- filetype=filetype).encode_hdr(boundary)298-299-def 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) + 6304-305-def 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 headers313-314-class multipart_yielder:315- def __init__(self, params, boundary, cb):316- self.params = params317- self.boundary = boundary318- self.cb = cb319-320- self.i = 0321- self.p = None322- self.param_iter = None323- self.current = 0324- self.total = get_body_size(params, boundary)325-326- def __iter__(self):327- return self328-329- 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 = None342-343- 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 block354-355- self.p = self.params[self.i]356- self.param_iter = self.p.iter_encode(self.boundary)357- self.i += 1358- return self.next()359-360- def reset(self):361- self.i = 0362- self.current = 0363- for param in self.params:364- param.reset()365-366-def multipart_encode(params, boundary=None, cb=None):367- """Encode ``params`` as multipart/form-data.368-369- ``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().374-375- 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.379-380- 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.384-385- 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.389-390- Examples:391-392- >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )393- >>> s = "".join(datagen)394- >>> assert "value2" in s and "value1" in s395-396- >>> p = MultipartParam("key", "value2")397- >>> datagen, headers = multipart_encode( [("key", "value1"), p] )398- >>> s = "".join(datagen)399- >>> assert "value2" in s and "value1" in s400-401- >>> datagen, headers = multipart_encode( {"key": "value1"} )402- >>> s = "".join(datagen)403- >>> assert "value2" not in s and "value1" in s404-405- """406- if boundary is None:407- boundary = gen_boundary()408- else:409- boundary = urllib.quote_plus(boundary)410-411- headers = get_headers(params, boundary)412- params = MultipartParam.from_params(params)413-414- return multipart_yielder(params, boundary, cb), headersdeleted:requests/packages/poster/streaminghttp.py-199 removed
1-"""Streaming HTTP uploads module.2-3-This module extends the standard httplib and urllib2 objects so that4-iterable objects can be used in the body of HTTP requests.5-6-In most cases all one should have to do is call :func:`register_openers()`7-to register the new streaming http handlers which will take priority over8-the default handlers, and then you can use iterable objects in the body9-of HTTP requests.10-11-**N.B.** You must specify a Content-Length header if using an iterable object12-since there is no way to determine in advance the total size that will be13-yielded, and there is no way to reset an interator.14-15-Example usage:16-17->>> from StringIO import StringIO18->>> import urllib2, poster.streaminghttp19-20->>> opener = poster.streaminghttp.register_openers()21-22->>> s = "Test file data"23->>> f = StringIO(s)24-25->>> req = urllib2.Request("http://localhost:5000", f,26-... {'Content-Length': str(len(s))})27-"""28-29-import httplib, urllib2, socket30-from httplib import NotConnected31-32-__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',33- 'StreamingHTTPHandler', 'register_openers']34-35-if hasattr(httplib, 'HTTPS'):36- __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])37-38-class _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.43-44- ``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()54-55- # 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- raise86-87-class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):88- """Subclass of `httplib.HTTPConnection` that overrides the `send()` method89- to support iterable body objects"""90-91-class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):92- """Subclass of `urllib2.HTTPRedirectHandler` that overrides the93- `redirect_request` method to properly handle redirected POST requests94-95- 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- """99-100- handler_order = urllib2.HTTPRedirectHandler.handler_order - 1101-102- # 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.105-106- 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)133-134-class StreamingHTTPHandler(urllib2.HTTPHandler):135- """Subclass of `urllib2.HTTPHandler` that uses136- StreamingHTTPConnection as its http connection class."""137-138- handler_order = urllib2.HTTPHandler.handler_order - 1139-140- def http_open(self, req):141- """Open a StreamingHTTPConnection for the given request"""142- return self.do_open(StreamingHTTPConnection, req)143-144- 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)156-157-if 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"""162-163- class StreamingHTTPSHandler(urllib2.HTTPSHandler):164- """Subclass of `urllib2.HTTPSHandler` that uses165- StreamingHTTPSConnection as its http connection class."""166-167- handler_order = urllib2.HTTPSHandler.handler_order - 1168-169- def https_open(self, req):170- return self.do_open(StreamingHTTPSConnection, req)171-172- 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)182-183-184-def get_handlers():185- handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186- if hasattr(httplib, "HTTPS"):187- handlers.append(StreamingHTTPSHandler)188- return handlers189- 190-def register_openers():191- """Register the streaming http handlers in the global urllib2 default192- opener object.193-194- Returns the created OpenerDirector object."""195- opener = urllib2.build_opener(*get_handlers())196-197- urllib2.install_opener(opener)198-199- return openeradded: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.php6+7+"""8+NTLM authenticating pool, contributed by erikcederstran9+10+Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011+"""12+13+import httplib14+from logging import getLogger15+from ntlm import ntlm16+17+from urllib3 import HTTPSConnectionPool18+19+20+log = getLogger(__name__)21+22+23+class NTLMConnectionPool(HTTPSConnectionPool):24+ """25+ Implements an NTLM authentication version of an urllib3 connection pool26+ """27+28+ scheme = 'https'29+30+ 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 = pw43+44+ 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))50+51+ headers = {}52+ headers['Connection'] = 'Keep-Alive'53+ req_header = 'Authorization'54+ resp_header = 'www-authenticate'55+56+ conn = httplib.HTTPSConnection(host=self.host, port=self.port)57+58+ # 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))68+69+ # 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 = None72+73+ # 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]))82+83+ # 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))104+105+ res.fp = None106+ log.debug('Connection established')107+ return conn108+109+ 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
1+from __future__ import with_statement2+3+4+# Copyright 2007 Google, Inc. All Rights Reserved.5+# Licensed to PSF under a Contributor Agreement.6+7+"""Abstract Base Classes (ABCs) according to PEP 3119."""8+9+import types10+11+from _weakref import ref12+13+__all__ = ['WeakSet']14+15+16+class _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).21+22+ def __init__(self, weakcontainer):23+ # Don't create cycles24+ self.weakcontainer = ref(weakcontainer)25+26+ def __enter__(self):27+ w = self.weakcontainer()28+ if w is not None:29+ w._iterating.add(self)30+ return self31+32+ 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()39+40+41+class 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)57+58+ def _commit_removals(self):59+ l = self._pending_removals60+ discard = self.data.discard61+ while l:62+ discard(l.pop())63+64+ def __iter__(self):65+ with _IterationGuard(self):66+ for itemref in self.data:67+ item = itemref()68+ if item is not None:69+ yield item70+71+ def __len__(self):72+ return sum(x() is not None for x in self.data)73+74+ def __contains__(self, item):75+ try:76+ wr = ref(item)77+ except TypeError:78+ return False79+ return wr in self.data80+81+ def __reduce__(self):82+ return (self.__class__, (list(self),),83+ getattr(self, '__dict__', None))84+85+ __hash__ = None86+87+ def add(self, item):88+ if self._pending_removals:89+ self._commit_removals()90+ self.data.add(ref(item, self._remove))91+92+ def clear(self):93+ if self._pending_removals:94+ self._commit_removals()95+ self.data.clear()96+97+ def copy(self):98+ return self.__class__(self)99+100+ 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 item111+112+ def remove(self, item):113+ if self._pending_removals:114+ self._commit_removals()115+ self.data.remove(ref(item))116+117+ def discard(self, item):118+ if self._pending_removals:119+ self._commit_removals()120+ self.data.discard(ref(item))121+122+ 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)130+131+ def __ior__(self, other):132+ self.update(other)133+ return self134+135+ # 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 newset143+144+ def difference(self, other):145+ return self._apply(other, self.data.difference)146+ __sub__ = difference147+148+ 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 self163+164+ def intersection(self, other):165+ return self._apply(other, self.data.intersection)166+ __and__ = intersection167+168+ 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 self177+178+ def issubset(self, other):179+ return self.data.issubset(ref(item) for item in other)180+ __lt__ = issubset181+182+ def __le__(self, other):183+ return self.data <= set(ref(item) for item in other)184+185+ def issuperset(self, other):186+ return self.data.issuperset(ref(item) for item in other)187+ __gt__ = issuperset188+189+ def __ge__(self, other):190+ return self.data >= set(ref(item) for item in other)191+192+ def __eq__(self, other):193+ if not isinstance(other, self.__class__):194+ return NotImplemented195+ return self.data == set(ref(item) for item in other)196+197+ def symmetric_difference(self, other):198+ return self._apply(other, self.data.symmetric_difference)199+ __xor__ = symmetric_difference200+201+ 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 self216+217+ def union(self, other):218+ return self._apply(other, self.data.union)219+ __or__ = union220+221+ def isdisjoint(self, other):222+ return len(self.intersection(other)) == 0223+224+225+# Instance of old-style class226+class _C: pass227+_InstanceType = type(_C())228+229+230+def abstractmethod(funcobj):231+ """A decorator indicating abstract methods.232+233+ 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.238+239+ Usage:240+241+ class C:242+ __metaclass__ = ABCMeta243+ @abstractmethod244+ def my_abstract_method(self, ...):245+ ...246+ """247+ funcobj.__isabstractmethod__ = True248+ return funcobj249+250+251+class abstractproperty(property):252+ """A decorator indicating abstract properties.253+254+ 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.259+260+ Usage:261+262+ class C:263+ __metaclass__ = ABCMeta264+ @abstractproperty265+ def my_abstract_property(self):266+ ...267+268+ This defines a read-only property; you can also define a read-write269+ abstract property using the 'long' form of property declaration:270+271+ class C:272+ __metaclass__ = ABCMeta273+ def getx(self): ...274+ def setx(self, value): ...275+ x = abstractproperty(getx, setx)276+ """277+ __isabstractmethod__ = True278+279+280+class ABCMeta(type):281+282+ """Metaclass for defining Abstract Base Classes (ABCs).283+284+ 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()).293+294+ """295+296+ # 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 = 0300+301+ 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 cls319+320+ 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 cache333+334+ 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)342+343+ 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))362+363+ 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 False401+402+403+404+405+406+407+408+409+import sys410+411+### ONE-TRICK PONIES ###412+413+def _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)419+420+421+class Hashable:422+ __metaclass__ = ABCMeta423+424+ @abstractmethod425+ def __hash__(self):426+ return 0427+428+ @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 NotImplemented442+443+444+class Iterable:445+ __metaclass__ = ABCMeta446+447+ @abstractmethod448+ def __iter__(self):449+ while False:450+ yield None451+452+ @classmethod453+ def __subclasshook__(cls, C):454+ if cls is Iterable:455+ if _hasattr(C, "__iter__"):456+ return True457+ return NotImplemented458+459+Iterable.register(str)460+461+462+class Iterator(Iterable):463+464+ @abstractmethod465+ def next(self):466+ raise StopIteration467+468+ def __iter__(self):469+ return self470+471+ @classmethod472+ def __subclasshook__(cls, C):473+ if cls is Iterator:474+ if _hasattr(C, "next") and _hasattr(C, "__iter__"):475+ return True476+ return NotImplemented477+478+479+class Sized:480+ __metaclass__ = ABCMeta481+482+ @abstractmethod483+ def __len__(self):484+ return 0485+486+ @classmethod487+ def __subclasshook__(cls, C):488+ if cls is Sized:489+ if _hasattr(C, "__len__"):490+ return True491+ return NotImplemented492+493+494+class Container:495+ __metaclass__ = ABCMeta496+497+ @abstractmethod498+ def __contains__(self, x):499+ return False500+501+ @classmethod502+ def __subclasshook__(cls, C):503+ if cls is Container:504+ if _hasattr(C, "__contains__"):505+ return True506+ return NotImplemented507+508+509+class Callable:510+ __metaclass__ = ABCMeta511+512+ @abstractmethod513+ def __call__(self, *args, **kwds):514+ return False515+516+ @classmethod517+ def __subclasshook__(cls, C):518+ if cls is Callable:519+ if _hasattr(C, "__call__"):520+ return True521+ return NotImplemented522+523+524+### SETS ###525+526+527+class Set(Sized, Iterable, Container):528+ """A set is a finite, iterable container.529+530+ This class provides concrete generic implementations of all531+ methods except for __contains__, __iter__ and __len__.532+533+ 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+ """537+538+ 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 True547+548+ def __lt__(self, other):549+ if not isinstance(other, Set):550+ return NotImplemented551+ return len(self) < len(other) and self.__le__(other)552+553+ def __gt__(self, other):554+ if not isinstance(other, Set):555+ return NotImplemented556+ return other < self557+558+ def __ge__(self, other):559+ if not isinstance(other, Set):560+ return NotImplemented561+ return other <= self562+563+ def __eq__(self, other):564+ if not isinstance(other, Set):565+ return NotImplemented566+ return len(self) == len(other) and self.__le__(other)567+568+ def __ne__(self, other):569+ return not (self == other)570+571+ @classmethod572+ def _from_iterable(cls, it):573+ '''Construct an instance of the class from any iterable input.574+575+ Must override this method if the class constructor signature576+ does not accept an iterable for an input.577+ '''578+ return cls(it)579+580+ 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)584+585+ def isdisjoint(self, other):586+ for value in other:587+ if value in self:588+ return False589+ return True590+591+ 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)596+597+ 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)604+605+ 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)611+612+ # Sets are not hashable by default, but subclasses can change this613+ __hash__ = None614+615+ def _hash(self):616+ """Compute the hash value of a set.617+618+ 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.621+622+ This must be compatible __eq__.623+624+ 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 h646+647+Set.register(frozenset)648+649+650+class MutableSet(Set):651+652+ @abstractmethod653+ def add(self, value):654+ """Add an element."""655+ raise NotImplementedError656+657+ @abstractmethod658+ def discard(self, value):659+ """Remove an element. Do not raise an exception if absent."""660+ raise NotImplementedError661+662+ 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)667+668+ 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 value677+678+ 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+ pass685+686+ def __ior__(self, it):687+ for value in it:688+ self.add(value)689+ return self690+691+ def __iand__(self, it):692+ for value in (self - it):693+ self.discard(value)694+ return self695+696+ 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 self708+709+ 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 self716+717+MutableSet.register(set)718+719+720+### MAPPINGS ###721+722+723+class Mapping(Sized, Iterable, Container):724+725+ @abstractmethod726+ def __getitem__(self, key):727+ raise KeyError728+729+ def get(self, key, default=None):730+ try:731+ return self[key]732+ except KeyError:733+ return default734+735+ def __contains__(self, key):736+ try:737+ self[key]738+ except KeyError:739+ return False740+ else:741+ return True742+743+ def iterkeys(self):744+ return iter(self)745+746+ def itervalues(self):747+ for key in self:748+ yield self[key]749+750+ def iteritems(self):751+ for key in self:752+ yield (key, self[key])753+754+ def keys(self):755+ return list(self)756+757+ def items(self):758+ return [(key, self[key]) for key in self]759+760+ def values(self):761+ return [self[key] for key in self]762+763+ # Mappings are not hashable by default, but subclasses can change this764+ __hash__ = None765+766+ def __eq__(self, other):767+ if not isinstance(other, Mapping):768+ return NotImplemented769+ return dict(self.items()) == dict(other.items())770+771+ def __ne__(self, other):772+ return not (self == other)773+774+class MappingView(Sized):775+776+ def __init__(self, mapping):777+ self._mapping = mapping778+779+ def __len__(self):780+ return len(self._mapping)781+782+ def __repr__(self):783+ return '{0.__class__.__name__}({0._mapping!r})'.format(self)784+785+786+class KeysView(MappingView, Set):787+788+ @classmethod789+ def _from_iterable(self, it):790+ return set(it)791+792+ def __contains__(self, key):793+ return key in self._mapping794+795+ def __iter__(self):796+ for key in self._mapping:797+ yield key798+799+800+class ItemsView(MappingView, Set):801+802+ @classmethod803+ def _from_iterable(self, it):804+ return set(it)805+806+ def __contains__(self, item):807+ key, value = item808+ try:809+ v = self._mapping[key]810+ except KeyError:811+ return False812+ else:813+ return v == value814+815+ def __iter__(self):816+ for key in self._mapping:817+ yield (key, self._mapping[key])818+819+820+class ValuesView(MappingView):821+822+ def __contains__(self, value):823+ for key in self._mapping:824+ if value == self._mapping[key]:825+ return True826+ return False827+828+ def __iter__(self):829+ for key in self._mapping:830+ yield self._mapping[key]831+832+833+class MutableMapping(Mapping):834+835+ @abstractmethod836+ def __setitem__(self, key, value):837+ raise KeyError838+839+ @abstractmethod840+ def __delitem__(self, key):841+ raise KeyError842+843+ __marker = object()844+845+ 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 value855+856+ 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, value864+865+ def clear(self):866+ try:867+ while True:868+ self.popitem()869+ except KeyError:870+ pass871+872+ 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 ()880+881+ 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] = value892+893+ def setdefault(self, key, default=None):894+ try:895+ return self[key]896+ except KeyError:897+ self[key] = default898+ return default899+900+MutableMapping.register(dict)901+902+903+### SEQUENCES ###904+905+906+class Sequence(Sized, Iterable, Container):907+ """All the operations on a read-only sequence.908+909+ Concrete subclasses must override __new__ or __init__,910+ __getitem__, and __len__.911+ """912+913+ @abstractmethod914+ def __getitem__(self, index):915+ raise IndexError916+917+ def __iter__(self):918+ i = 0919+ try:920+ while True:921+ v = self[i]922+ yield v923+ i += 1924+ except IndexError:925+ return926+927+ def __contains__(self, value):928+ for v in self:929+ if v == value:930+ return True931+ return False932+933+ def __reversed__(self):934+ for i in reversed(range(len(self))):935+ yield self[i]936+937+ def index(self, value):938+ for i, v in enumerate(self):939+ if v == value:940+ return i941+ raise ValueError942+943+ def count(self, value):944+ return sum(1 for v in self if v == value)945+946+Sequence.register(tuple)947+Sequence.register(basestring)948+Sequence.register(buffer)949+Sequence.register(xrange)950+951+952+class MutableSequence(Sequence):953+954+ @abstractmethod955+ def __setitem__(self, index, value):956+ raise IndexError957+958+ @abstractmethod959+ def __delitem__(self, index):960+ raise IndexError961+962+ @abstractmethod963+ def insert(self, index, value):964+ raise IndexError965+966+ def append(self, value):967+ self.insert(len(self), value)968+969+ 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]973+974+ def extend(self, values):975+ for v in values:976+ self.append(v)977+978+ def pop(self, index=-1):979+ v = self[index]980+ del self[index]981+ return v982+983+ def remove(self, value):984+ del self[self.index(value)]985+986+ def __iadd__(self, values):987+ self.extend(values)988+ return self989+990+MutableSequence.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.php6+7+"""8+urllib3 - Thread-safe connection pooling and re-using.9+"""10+11+__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12+__license__ = 'MIT'13+__version__ = '1.0.2'14+15+16+from .connectionpool import (17+ HTTPConnectionPool,18+ HTTPSConnectionPool,19+ connection_from_url,20+ get_host,21+ make_headers)22+23+24+from .exceptions import (25+ HTTPError,26+ MaxRetryError,27+ SSLError,28+ TimeoutError)29+30+from .poolmanager import PoolManager, ProxyManager, proxy_from_url31+from .response import HTTPResponse32+from .filepost import encode_multipart_formdata33+34+35+# Set default logging handler to avoid "No handler found" warnings.36+import logging37+try:38+ from logging import NullHandler39+except ImportError:40+ class NullHandler(logging.Handler):41+ def emit(self, record):42+ pass43+44+logging.getLogger(__name__).addHandler(NullHandler())45+46+# ... Clean up.47+del logging48+del NullHandleradded: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.php6+7+8+from collections import deque9+from threading import RLock10+11+try:12+ from collections import MutableMapping13+except ImportError:14+ from .__collections import MutableMapping15+16+__all__ = ['RecentlyUsedContainer']17+18+19+class AccessEntry(object):20+ __slots__ = ('key', 'is_valid')21+22+ def __init__(self, key, is_valid=True):23+ self.key = key24+ self.is_valid = is_valid25+26+27+class 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+ """32+33+ # 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 = 1037+38+ def __init__(self, maxsize=10):39+ self._maxsize = maxsize40+41+ self._container = {}42+43+ # 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()46+47+ # 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 = {}51+52+ # Trigger a heap cleanup when we get past this size53+ self.access_log_limit = maxsize * self.CLEANUP_FACTOR54+55+ 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 = False60+61+ return old_entry62+63+ def _push_entry(self, key):64+ "Push entry onto our access log, invalidate the old entry if exists."65+ self._invalidate_entry(key)66+67+ new_entry = AccessEntry(key)68+ self.access_lookup[key] = new_entry69+70+ self.access_log_lock.acquire()71+ self.access_log.appendleft(new_entry)72+ self.access_log_lock.release()73+74+ 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()80+81+ if not p.is_valid:82+ continue # Invalidated entry, skip83+84+ self._container.pop(p.key, None)85+ self.access_lookup.pop(p.key, None)86+ num -= 187+88+ 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()93+94+ 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()99+100+ return r101+102+ def __getitem__(self, key):103+ item = self._container.get(key)104+105+ if not item:106+ raise KeyError(key)107+108+ # Insert new entry with new high priority, also implicitly invalidates109+ # the old entry.110+ self._push_entry(key)111+112+ 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()116+117+ return item118+119+ def __setitem__(self, key, item):120+ # Add item to our container and access log121+ self._container[key] = item122+ self._push_entry(key)123+124+ # Discard invalid and excess entries125+ self._prune_entries(len(self._container) - self._maxsize)126+127+ def __delitem__(self, key):128+ self._invalidate_entry(key)129+ del self._container[key]130+ del self.access_lookup[key]131+132+ def __len__(self):133+ return self._container.__len__()134+135+ def __iter__(self):136+ return self._container.__iter__()137+138+ 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.php6+7+import logging8+import socket9+10+11+from httplib import HTTPConnection, HTTPSConnection, HTTPException12+from Queue import Queue, Empty, Full13+from select import select14+from socket import error as SocketError, timeout as SocketTimeout15+16+17+try:18+ import ssl19+ BaseSSLError = ssl.SSLError20+except ImportError:21+ ssl = None22+ BaseSSLError = None23+24+25+from .request import RequestMethods26+from .response import HTTPResponse27+from .exceptions import (28+ SSLError,29+ MaxRetryError,30+ TimeoutError,31+ HostChangedError,32+ EmptyPoolError,33+)34+35+36+log = logging.getLogger(__name__)37+38+_Default = object()39+40+41+## Connection objects (extension of httplib)42+43+class VerifiedHTTPSConnection(HTTPSConnection):44+ """45+ Based on httplib.HTTPSConnection but wraps the socket with46+ SSL certification.47+ """48+ cert_reqs = None49+ ca_certs = None50+51+ def set_cert(self, key_file=None, cert_file=None,52+ cert_reqs='CERT_NONE', ca_certs=None):53+ ssl_req_scheme = {54+ 'CERT_NONE': ssl.CERT_NONE,55+ 'CERT_OPTIONAL': ssl.CERT_OPTIONAL,56+ 'CERT_REQUIRED': ssl.CERT_REQUIRED57+ }58+59+ 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_certs63+64+ def connect(self):65+ # Add certificate verification66+ sock = socket.create_connection((self.host, self.port), self.timeout)67+68+ # 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)73+74+75+## Pool objects76+77+class ConnectionPool(object):78+ """79+ Base class for all connection pools, such as80+ :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.81+ """82+ pass83+84+85+class HTTPConnectionPool(ConnectionPool, RequestMethods):86+ """87+ Thread-safe connection pool for one host.88+89+ :param host:90+ Host used for this HTTP Connection (e.g. "localhost"), passed into91+ :class:`httplib.HTTPConnection`.92+93+ :param port:94+ Port used for this HTTP Connection (None is equivalent to 80), passed95+ into :class:`httplib.HTTPConnection`.96+97+ :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`.101+102+ :param timeout:103+ Socket timeout for each individual connection, can be a float. None104+ disables timeout.105+106+ :param maxsize:107+ Number of connections to save that can be reused. More than 1 is useful108+ in multithreaded situations. If ``block`` is set to false, more109+ connections will be created but they will not be saved once they've110+ been used.111+112+ :param block:113+ If set to True, no more than ``maxsize`` connections will be used at114+ a time. When no free connections are available, the call will block115+ until a connection has been released. This is a useful side effect for116+ particular multithreaded situations where one does not want to use more117+ than maxsize connections per host to prevent flooding.118+119+ :param headers:120+ Headers to include with all requests, unless other headers are given121+ explicitly.122+ """123+124+ scheme = 'http'125+126+ 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 {}135+136+ # Fill the queue up so that doing get() on it will block properly137+ for _ in xrange(maxsize):138+ self.pool.put(None)139+140+ # These are mostly for testing and debugging purposes.141+ self.num_connections = 0142+ self.num_requests = 0143+144+ 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)152+153+ def _get_conn(self, timeout=None):154+ """155+ Get a connection. Will return a pooled connection if one is available.156+157+ If no connections are available and :prop:`.block` is ``False``, then a158+ fresh connection is returned.159+160+ :param timeout:161+ Seconds to wait before giving up and raising162+ :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and163+ :prop:`.block` is ``True``.164+ """165+ conn = None166+ try:167+ conn = self.pool.get(block=self.block, timeout=timeout)168+169+ # 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()174+175+ 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 then180+181+ return conn or self._new_conn()182+183+ def _put_conn(self, conn):184+ """185+ Put a connection back into the pool.186+187+ :param conn:188+ Connection object for the current host and port as returned by189+ :meth:`._new_conn` or :meth:`._get_conn`.190+191+ If the pool is already full, the connection is discarded because we192+ exceeded maxsize. If connections are discarded frequently, then maxsize193+ should be increased.194+ """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)201+202+ 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 += 1209+210+ if timeout is _Default:211+ timeout = self.timeout212+213+ conn.request(method, url, **httplib_request_kw)214+ conn.sock.settimeout(timeout)215+ httplib_response = conn.getresponse()216+217+ log.debug("\"%s %s %s\" %s %s" %218+ (method, url,219+ conn._http_vsn_str, # pylint: disable-msg=W0212220+ httplib_response.status, httplib_response.length))221+222+ return httplib_response223+224+225+ def is_same_host(self, url):226+ """227+ Check if the given ``url`` is a member of the same host as this228+ conncetion pool.229+ """230+ # TODO: Add optional support for socket.gethostbyname checking.231+ return (url.startswith('/') or232+ get_host(url) == (self.scheme, self.host, self.port))233+234+ def urlopen(self, method, url, body=None, headers=None, retries=3,235+ redirect=True, assert_same_host=True, timeout=_Default,236+ pool_timeout=None, release_conn=None, **response_kw):237+ """238+ Get a connection from the pool and perform an HTTP request. This is the239+ lowest level call for making a request, so you'll need to specify all240+ the raw details.241+242+ .. note::243+244+ More commonly, it's appropriate to use a convenience method provided245+ by :class:`.RequestMethods`, such as :meth:`.request`.246+247+ :param method:248+ HTTP request method (such as GET, POST, PUT, etc.)249+250+ :param body:251+ Data to send in the request body (useful for creating252+ POST requests, see HTTPConnectionPool.post_url for253+ more convenience).254+255+ :param headers:256+ Dictionary of custom headers to send, such as User-Agent,257+ If-None-Match, etc. If None, pool headers are used. If provided,258+ these headers completely replace any pool-specific headers.259+260+ :param retries:261+ Number of retries to allow before raising a MaxRetryError exception.262+263+ :param redirect:264+ Automatically handle redirects (status codes 301, 302, 303, 307),265+ each redirect counts as a retry.266+267+ :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.271+272+ :param timeout:273+ If specified, overrides the default timeout for this one request.274+275+ :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.279+280+ :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)``.287+288+ :param \**response_kw:289+ Additional parameters are passed to290+ :meth:`urllib3.response.HTTPResponse.from_httplib`291+ """292+ if headers is None:293+ headers = self.headers294+295+ if retries < 0:296+ raise MaxRetryError("Max retries exceeded for url: %s" % url)297+298+ if release_conn is None:299+ release_conn = response_kw.get('preload_content', True)300+301+ # 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)306+307+ raise HostChangedError("Connection pool with host '%s' tried to "308+ "open a foreign host: %s" % (host, url))309+310+ conn = None311+312+ try:313+ # Request a connection from the queue314+ # (Could raise SocketError: Bad file descriptor)315+ conn = self._get_conn(timeout=pool_timeout)316+317+ # Make the request on the httplib connection object318+ httplib_response = self._make_request(conn, method, url,319+ timeout=timeout,320+ body=body, headers=headers)321+322+ # 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 conn327+328+ # 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)333+334+ # else:335+ # The connection will be put back into the pool when336+ # ``response.release_conn()`` is called (implicitly by337+ # ``response.read()``)338+339+ except (SocketTimeout, Empty), e:340+ # Timed out either by socket or queue341+ raise TimeoutError("Request timed out after %s seconds" %342+ self.timeout)343+344+ except (BaseSSLError), e:345+ # SSL certificate error346+ raise SSLError(e)347+348+ except (HTTPException, SocketError), e:349+ # Connection broken, discard. It will be replaced next _get_conn().350+ conn = None351+352+ finally:353+ if conn and release_conn:354+ # Put the connection back to be reused355+ self._put_conn(conn)356+357+ 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 again362+363+ # 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)372+373+ return response374+375+376+class HTTPSConnectionPool(HTTPConnectionPool):377+ """378+ Same as :class:`.HTTPConnectionPool`, but HTTPS.379+380+ When Python is compiled with the :mod:`ssl` module, then381+ :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,382+ instead of :class:httplib.HTTPSConnection`.383+384+ 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+ """388+389+ scheme = 'https'390+391+ 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):396+397+ 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_certs404+405+ 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))412+413+ if not ssl:414+ return HTTPSConnection(host=self.host, port=self.port)415+416+ 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 connection420+421+422+## Helpers423+424+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,425+ basic_auth=None):426+ """427+ Shortcuts for generating request headers.428+429+ :param keep_alive:430+ If ``True``, adds 'connection: keep-alive' header.431+432+ :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.437+438+ :param user_agent:439+ String representing the user-agent you want, such as440+ "python-urllib3/0.6"441+442+ :param basic_auth:443+ Colon-separated username:password string for 'authorization: basic ...'444+ auth header.445+446+ Example: ::447+448+ >>> 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_encoding462+463+ if user_agent:464+ headers['user-agent'] = user_agent465+466+ if keep_alive:467+ headers['connection'] = 'keep-alive'468+469+ if basic_auth:470+ headers['authorization'] = 'Basic ' + \471+ basic_auth.encode('base64').strip()472+473+ return headers474+475+476+def get_host(url):477+ """478+ Given a url, return its scheme, host and port (None if it's not there).479+480+ For example: ::481+482+ >>> 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, port499+500+501+def connection_from_url(url, **kw):502+ """503+ Given a url, return an :class:`.ConnectionPool` instance of its host.504+505+ This is a shortcut for not having to parse out the scheme, host, and port506+ of the url before creating an :class:`.ConnectionPool` instance.507+508+ :param url:509+ Absolute URL string that must include the scheme. Port is optional.510+511+ :param \**kw:512+ Passes additional parameters to the constructor of the appropriate513+ :class:`.ConnectionPool`. Useful for specifying things like514+ timeout, maxsize, headers, etc.515+516+ Example: ::517+518+ >>> 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.php6+7+## Exceptions8+9+class HTTPError(Exception):10+ "Base exception used by this module."11+ pass12+13+14+class SSLError(Exception):15+ "Raised when SSL certificate fails in an HTTPS connection."16+ pass17+18+19+class MaxRetryError(HTTPError):20+ "Raised when the maximum number of retries is exceeded."21+ pass22+23+24+class TimeoutError(HTTPError):25+ "Raised when a socket timeout occurs."26+ pass27+28+29+class HostChangedError(HTTPError):30+ "Raised when an existing pool gets a request for a foreign host."31+ pass32+33+class EmptyPoolError(HTTPError):34+ "Raised when a pool runs out of connections and no more are allowed."35+ passadded: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.php6+7+import codecs8+import mimetools9+import mimetypes10+11+try:12+ from cStringIO import StringIO13+except ImportError:14+ from StringIO import StringIO # pylint: disable-msg=W040415+16+17+writer = codecs.lookup('utf-8')[3]18+19+20+def get_content_type(filename):21+ return mimetypes.guess_type(filename)[0] or 'application/octet-stream'22+23+24+def encode_multipart_formdata(fields, boundary=None):25+ """26+ Encode a dictionary of ``fields`` using the multipart/form-data mime format.27+28+ :param fields:29+ Dictionary of fields. The key is treated as the field name, and the30+ value as the body of the form-data. If the value is a tuple of two31+ elements, then the first element is treated as the filename of the32+ form-data section.33+34+ :param boundary:35+ If not specified, then a random boundary will be generated using36+ :func:`mimetools.choose_boundary`.37+ """38+ body = StringIO()39+ if boundary is None:40+ boundary = mimetools.choose_boundary()41+42+ for fieldname, value in fields.iteritems():43+ body.write('--%s\r\n' % (boundary))44+45+ 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')56+57+ if isinstance(data, int):58+ data = str(data) # Backwards compatibility59+60+ if isinstance(data, unicode):61+ writer(body).write(data)62+ else:63+ body.write(data)64+65+ body.write('\r\n')66+67+ body.write('--%s--\r\n' % (boundary))68+69+ content_type = 'multipart/form-data; boundary=%s' % boundary70+71+ return body.getvalue(), content_typeadded: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.php6+7+from ._collections import RecentlyUsedContainer8+from .connectionpool import (9+ HTTPConnectionPool, HTTPSConnectionPool,10+ get_host, connection_from_url,11+)12+13+14+__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']15+16+17+from .request import RequestMethods18+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool19+20+21+pool_classes_by_scheme = {22+ 'http': HTTPConnectionPool,23+ 'https': HTTPSConnectionPool,24+}25+26+port_by_scheme = {27+ 'http': 80,28+ 'https': 443,29+}30+31+32+class PoolManager(RequestMethods):33+ """34+ Allows for arbitrary requests while transparently keeping track of35+ necessary connection pools for you.36+37+ :param num_pools:38+ Number of connection pools to cache before discarding the least recently39+ used pool.40+41+ :param \**connection_pool_kw:42+ Additional parameters are used to create fresh43+ :class:`urllib3.connectionpool.ConnectionPool` instances.44+45+ Example: ::46+47+ >>> manager = PoolManager()48+ >>> r = manager.urlopen("http://google.com/")49+ >>> r = manager.urlopen("http://google.com/mail")50+ >>> r = manager.urlopen("http://yahoo.com/")51+ >>> len(r.pools)52+ 253+54+ """55+56+ # TODO: Make sure there are no memory leaks here.57+58+ def __init__(self, num_pools=10, **connection_pool_kw):59+ self.connection_pool_kw = connection_pool_kw60+ self.pools = RecentlyUsedContainer(num_pools)61+62+ def connection_from_host(self, host, port=80, scheme='http'):63+ """64+ Get a :class:`ConnectionPool` based on the host, port, and scheme.65+66+ Note that an appropriate ``port`` value is required here to normalize67+ connection pools in our container most effectively.68+ """69+ pool_key = (scheme, host, port)70+71+ # If the scheme, host, or port doesn't match existing open connections,72+ # open a new ConnectionPool.73+ pool = self.pools.get(pool_key)74+ if pool:75+ return pool76+77+ # 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)80+81+ self.pools[pool_key] = pool82+83+ return pool84+85+ 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.90+91+ Additional parameters are taken from the :class:`.PoolManager`92+ constructor.93+ """94+ scheme, host, port = get_host(url)95+96+ port = port or port_by_scheme.get(scheme, 80)97+98+ return self.connection_from_host(host, port=port, scheme=scheme)99+100+ def urlopen(self, method, url, **kw):101+ """102+ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.103+104+ ``url`` must be absolute, such that an appropriate105+ :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.106+ """107+ conn = self.connection_from_url(url)108+ return conn.urlopen(method, url, assert_same_host=False, **kw)109+110+111+class ProxyManager(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+ """116+117+ def __init__(self, proxy_pool):118+ self.proxy_pool = proxy_pool119+120+ def urlopen(self, method, url, **kw):121+ "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."122+ kw['assert_same_host'] = False123+ return self.proxy_pool.urlopen(method, url, **kw)124+125+126+def proxy_from_url(url, **pool_kw):127+ proxy_pool = connection_from_url(url, **pool_kw)128+ return ProxyManager(proxy_pool)added:requests/packages/urllib3/request.py+145 added
1+# urllib3/request.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+8+from urllib import urlencode9+10+from .filepost import encode_multipart_formdata11+12+13+__all__ = ['RequestMethods']14+15+16+class RequestMethods(object):17+ """18+ Convenience mixin for classes who implement a :meth:`urlopen` method, such19+ as :class:`~urllib3.connectionpool.HTTPConnectionPool` and20+ :class:`~urllib3.poolmanager.PoolManager`.21+22+ Provides behavior for making common types of HTTP request methods and23+ decides which type of request field encoding to use.24+25+ Specifically,26+27+ :meth:`.request_encode_url` is for sending requests whose fields are encoded28+ in the URL (such as GET, HEAD, DELETE).29+30+ :meth:`.request_encode_body` is for sending requests whose fields are31+ encoded in the *body* of the request using multipart or www-orm-urlencoded32+ (such as for POST, PUT, PATCH).33+34+ :meth:`.request` is for making any kind of request, it will look up the35+ appropriate encoding format and use one of the above two methods to make36+ the request.37+ """38+39+ _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])40+41+ _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])42+43+ def urlopen(self, method, url, body=None, headers=None,44+ encode_multipart=True, multipart_boundary=None,45+ **kw):46+ raise NotImplemented("Classes extending RequestMethods must implement "47+ "their own ``urlopen`` method.")48+49+ def request(self, method, url, fields=None, headers=None, **urlopen_kw):50+ """51+ Make a request using :meth:`urlopen` with the appropriate encoding of52+ ``fields`` based on the ``method`` used.53+54+ This is a convenience method that requires the least amount of manual55+ effort. It can be used in most situations, while still having the option56+ to drop down to more specific methods when necessary, such as57+ :meth:`request_encode_url`, :meth:`request_encode_body`,58+ or even the lowest level :meth:`urlopen`.59+ """60+ method = method.upper()61+62+ if method in self._encode_url_methods:63+ return self.request_encode_url(method, url, fields=fields,64+ headers=headers,65+ **urlopen_kw)66+ else:67+ return self.request_encode_body(method, url, fields=fields,68+ headers=headers,69+ **urlopen_kw)70+71+ def request_encode_url(self, method, url, fields=None, **urlopen_kw):72+ """73+ Make a request using :meth:`urlopen` with the ``fields`` encoded in74+ the url. This is useful for request methods like GET, HEAD, DELETE, etc.75+ """76+ if fields:77+ url += '?' + urlencode(fields)78+ return self.urlopen(method, url, **urlopen_kw)79+80+ def request_encode_body(self, method, url, fields=None, headers=None,81+ encode_multipart=True, multipart_boundary=None,82+ **urlopen_kw):83+ """84+ Make a request using :meth:`urlopen` with the ``fields`` encoded in85+ the body. This is useful for request methods like POST, PUT, PATCH, etc.86+87+ When ``encode_multipart=True`` (default), then88+ :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the89+ payload with the appropriate content type. Otherwise90+ :meth:`urllib.urlencode` is used with the91+ 'application/x-www-form-urlencoded' content type.92+93+ Multipart encoding must be used when posting files, and it's reasonably94+ safe to use it in other times too. However, it may break request signing,95+ such as with OAuth.96+97+ Supports an optional ``fields`` parameter of key/value strings AND98+ key/filetuple. A filetuple is a (filename, data) tuple. For example: ::99+100+ fields = {101+ 'foo': 'bar',102+ 'fakefile': ('foofile.txt', 'contents of foofile'),103+ 'realfile': ('barfile.txt', open('realfile').read()),104+ 'nonamefile': ('contents of nonamefile field'),105+ }106+107+ When uploading a file, providing a filename (the first parameter of the108+ tuple) is optional but recommended to best mimick behavior of browsers.109+110+ Note that if ``headers`` are supplied, the 'Content-Type' header will be111+ overwritten because it depends on the dynamic random boundary string112+ which is used to compose the body of the request. The random boundary113+ string can be explicitly set with the ``multipart_boundary`` parameter.114+ """115+ if encode_multipart:116+ body, content_type = encode_multipart_formdata(fields or {},117+ boundary=multipart_boundary)118+ else:119+ body, content_type = (urlencode(fields or {}),120+ 'application/x-www-form-urlencoded')121+122+ headers = headers or {}123+ headers.update({'Content-Type': content_type})124+125+ return self.urlopen(method, url, body=body, headers=headers,126+ **urlopen_kw)127+128+ # Deprecated:129+130+ def get_url(self, url, fields=None, **urlopen_kw):131+ """132+ .. deprecated:: 1.0133+ Use :meth:`request` instead.134+ """135+ return self.request_encode_url('GET', url, fields=fields,136+ **urlopen_kw)137+138+ def post_url(self, url, fields=None, headers=None, **urlopen_kw):139+ """140+ .. deprecated:: 1.0141+ Use :meth:`request` instead.142+ """143+ return self.request_encode_body('POST', url, fields=fields,144+ headers=headers,145+ **urlopen_kw)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.php6+7+import gzip8+import logging9+import zlib10+11+12+try:13+ from cStringIO import StringIO14+except ImportError:15+ from StringIO import StringIO # pylint: disable-msg=W040416+17+18+from .exceptions import HTTPError19+20+21+log = logging.getLogger(__name__)22+23+24+def decode_gzip(data):25+ gzipper = gzip.GzipFile(fileobj=StringIO(data))26+ return gzipper.read()27+28+29+def decode_deflate(data):30+ try:31+ return zlib.decompress(data)32+ except zlib.error:33+ return zlib.decompress(data, -zlib.MAX_WBITS)34+35+36+class HTTPResponse(object):37+ """38+ HTTP Response container.39+40+ Backwards-compatible to httplib's HTTPResponse but the response ``body`` is41+ loaded and decoded on-demand when the ``data`` property is accessed.42+43+ Extra parameters for behaviour not present in httplib.HTTPResponse:44+45+ :param preload_content:46+ If True, the response's body will be preloaded during construction.47+48+ :param decode_content:49+ If True, attempts to decode specific content-encoding's based on headers50+ (like 'gzip' and 'deflate') will be skipped and raw data will be used51+ instead.52+53+ :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+ """58+59+ CONTENT_DECODERS = {60+ 'gzip': decode_gzip,61+ 'deflate': decode_deflate,62+ }63+64+ 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 = strict72+73+ self._decode_content = decode_content74+ self._body = None75+ self._fp = None76+ self._original_response = original_response77+78+ self._pool = pool79+ self._connection = connection80+81+ if hasattr(body, 'read'):82+ self._fp = body83+84+ if preload_content:85+ self._body = self.read(decode_content=decode_content)86+87+ def release_conn(self):88+ if not self._pool or not self._connection:89+ return90+91+ self._pool._put_conn(self._connection)92+ self._connection = None93+94+ @property95+ def data(self):96+ # For backwords-compat with earlier urllib3 0.4 and earlier.97+ if self._body:98+ return self._body99+100+ if self._fp:101+ return self.read(decode_content=self._decode_content,102+ cache_content=True)103+104+ 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``.108+109+ :param amt:110+ How much of the content to read. If specified, decoding and caching111+ is skipped because we can't decode partial content nor does it make112+ sense to cache partial content as the full response.113+114+ :param decode_content:115+ If True, will attempt to decode the body based on the116+ 'content-encoding' header. (Overridden if ``amt`` is set.)117+118+ :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)127+128+ data = self._fp and self._fp.read(amt)129+130+ try:131+132+ if amt:133+ return data134+135+ if not decode_content or not decoder:136+ if cache_content:137+ self._body = data138+139+ return data140+141+ 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)146+147+ if cache_content:148+ self._body = data149+150+ return data151+152+ finally:153+154+ if self._original_response and self._original_response.isclosed():155+ self.release_conn()156+157+ @staticmethod158+ def from_httplib(r, **response_kw):159+ """160+ Given an :class:`httplib.HTTPResponse` instance ``r``, return a161+ corresponding :class:`urllib3.response.HTTPResponse` object.162+163+ Remaining parameters are passed to the HTTPResponse constructor, along164+ with ``original_response=r``.165+ """166+167+ 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)175+176+ # Backwards-compatibility methods for httplib.HTTPResponse177+ def getheaders(self):178+ return self.headers179+180+ def getheader(self, name, default=None):181+ return self.headers.get(name, default)modified:requests/packages/__init__.py+1 added-1 removed
1 from __future__ import absolute_import2 3-from . import poster3+from . import urllib3modified:requests/__init__.py+6 added-6 removed
13 unmodified lines14 15 """16 17 __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'23 24 25 from . import utils26 from .models import Request, Response27-from .api import request, get, head, post, patch, put, delete28-from .sessions import session27+from .api import request, get, head, post, patch, put, delete, options28+from .sessions import session, Session29 from .status_codes import codes30 from .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 lines12 """13 14 from .sessions import session15 16-__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')16 18-17 def request(method, url,18 params=None,19 data=None,20 headers=None,4 unmodified lines25 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 lines47 """48 49 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 )67 68 69 4 unmodified lines74 :param **kwargs: Optional arguments that ``request`` takes.75 """76 77 kwargs.setdefault('allow_redirects', True)67- return request('GET', url, **kwargs)78+ return request('get', url, **kwargs)79 80 81+def options(url, **kwargs):82+ """Sends a OPTIONS request. Returns :class:`Response` object.83+84+ :param url: URL for the new :class:`Request` object.85+ :param **kwargs: Optional arguments that ``request`` takes.86+ """87+88+ kwargs.setdefault('allow_redirects', True)89+ return request('options', url, **kwargs)90+91+92 def head(url, **kwargs):93 """Sends a HEAD request. Returns :class:`Response` object.94 95 :param url: URL for the new :class:`Request` object.96 :param **kwargs: Optional arguments that ``request`` takes.97 """98 99 kwargs.setdefault('allow_redirects', True)78- return request('HEAD', url, **kwargs)100+ return request('head', url, **kwargs)101 102 81-def post(url, data='', **kwargs):103+def post(url, data=None, **kwargs):104 """Sends a POST request. Returns :class:`Response` object.105 106 :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 lines110 111 return request('post', url, data=data, **kwargs)112 113 92-def put(url, data='', **kwargs):114+def put(url, data=None, **kwargs):115 """Sends a PUT request. Returns :class:`Response` object.116 117 :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 lines121 122 return request('put', url, data=data, **kwargs)123 124 103-def patch(url, data='', **kwargs):125+def patch(url, data=None, **kwargs):126 """Sends a PATCH request. Returns :class:`Response` object.127 128 :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 linesmodified:requests/async.py+13 added-5 removed
10 unmodified lines11 12 try:13 import gevent14 from gevent import monkey as curious_george15+ from gevent.pool import Pool16 except ImportError:17 raise RuntimeError('Gevent is required for requests.async.')18 19 # Monkey-patch.20 curious_george.patch_all(thread=False)21 22 from . import api22-from .hooks import dispatch_hook23 24 25 __all__ = (26 'map',27- 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'27+ 'get', 'options', 'head', 'post', 'put', 'patch', 'delete', 'request'28 )29 30 31 def patched(f):1 unmodified line33 34 def wrapped(*args, **kwargs):35 36 kwargs['return_response'] = False37+ kwargs['prefetch'] = True38 39 return f(*args, **kwargs)40 41 return wrapped11 unmodified lines53 54 55 # Patched requests.api functions.56 get = patched(api.get)57+options = patched(api.options)58 head = patched(api.head)59 post = patched(api.post)60 put = patched(api.put)61 patch = patched(api.patch)62 delete = patched(api.delete)63 request = patched(api.request)64 65 64-def map(requests, prefetch=True):66+def map(requests, prefetch=True, size=None):67 """Concurrently converts a list of Requests to Responses.68 69 :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 """73 74+ 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)81 82 if prefetch:83 [r.response.content for r in requests]84 5 unmodified linesmodified:requests/defaults.py+16 added-13 removed
4 unmodified lines5 ~~~~~~~~~~~~~~~~~6 7 This module provides the Requests configuration defaults.8 9-settings parameters:9+Configurations:10 11-- :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.21 22 """23 24 from . import __version__6 unmodified lines31 'Accept-Encoding': ', '.join(('identity', 'deflate', 'compress', 'gzip')),32 'Accept': '*/*'33 }34 32-defaults['proxies'] = {}35 defaults['verbose'] = None34-defaults['timeout'] = None36 defaults['max_redirects'] = 3037 defaults['decode_unicode'] = True37-defaults['timeout_fallback'] = True38-# defaults['keep_alive'] = True39-# defaults['max_connections'] = 1038+defaults['pool_connections'] = 1039+defaults['pool_maxsize'] = 1040+defaults['max_retries'] = 041+defaults['safe_mode'] = False42+defaults['keep_alive'] = Truemodified:requests/exceptions.py+5 added-2 removed
10 unmodified lines11 class RequestException(Exception):12 """There was an ambiguous exception that occurred while handling your13 request."""14 15-class AuthenticationError(RequestException):16- """The authentication credentials provided were invalid."""15+class HTTPError(RequestException):16+ """An HTTP error occured."""17 18+class ConnectionError(RequestException):19+ """A Connection error occured."""20+21 class Timeout(RequestException):22 """The request timed out."""23 24 class URLRequired(RequestException):4 unmodified linesmodified:requests/models.py+194 added-126 removed
3 unmodified lines4 """5 requests.models6 ~~~~~~~~~~~~~~~7 8+This module contains the primary objects that power Requests.9 """10 11 import urllib11-import urllib212-import socket12 import zlib13 14+from Cookie import SimpleCookie15 from urlparse import urlparse, urlunparse, urljoin16 from datetime import datetime17 18 from .auth import dispatch as auth_dispatch19 from .hooks import dispatch_hook20 from .structures import CaseInsensitiveDict21-from .packages.poster.encode import multipart_encode22-from .packages.poster.streaminghttp import register_openers, get_handlers21 from .status_codes import codes24-from .exceptions import Timeout, URLRequired, TooManyRedirects25-from .monkeys import Request as _Request26-from .monkeys import HTTPRedirectHandler22+from .packages.urllib3.exceptions import MaxRetryError23+from .packages.urllib3.exceptions import SSLError as _SSLError24+from .packages.urllib3.exceptions import HTTPError as _HTTPError25+from .packages.urllib3 import connectionpool, poolmanager26+from .packages.urllib3.filepost import encode_multipart_formdata27+from .exceptions import (28+ Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)29 from .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)32 33 34+35+36 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)37 38 39 15 unmodified lines55 redirect=False,56 allow_redirects=False,57 proxies=None,58 hooks=None,55- config=None):59+ config=None,60+ _poolmanager=None):61 62 #: Float describes the timeout of the request.63 # (Use socket.setdefaulttimeout() as fallback)64 self.timeout = timeout1 unmodified line66 #: Request URL.67 self.url = url68 69 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.65- self.headers = headers70+ self.headers = dict(headers or [])71 72 #: Dictionary of files to multipart upload (``{filename: content}``).73 self.files = files74 6 unmodified lines81 82 #: Dictionary or byte of querystring data to attach to the83 #: :class:`Request <Request>`.84 self.params = None85+ self.params = dict(params or [])86 87 #: True if :class:`Request <Request>` is part of a redirect chain (disables history88 #: and HTTPError storage).89 self.redirect = redirect1 unmodified line91 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)92 self.allow_redirects = allow_redirects93 94 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})89- self.proxies = proxies95+ self.proxies = dict(proxies or [])96 97 self.data, self._enc_data = self._encode_params(data)98 self.params, self._enc_params = self._encode_params(params)99 5 unmodified lines105 self._auth = auth106 self.auth = auth_dispatch(auth)107 108 #: CookieJar to attach to :class:`Request <Request>`.103- self.cookies = cookies109+ self.cookies = dict(cookies or [])110 111 #: Dictionary of configurations for this request.106- self.config = config112+ self.config = dict(config or [])113 114 #: True if Request has been sent.115 self.sent = False116 117 #: Event-handling hooks.118 self.hooks = hooks119 120+ #: Session.121+ self.session = None122+123 if headers:124 headers = CaseInsensitiveDict(self.headers)125 else:126 headers = CaseInsensitiveDict()2 unmodified lines129 if k not in headers:130 headers[k] = v131 132 self.headers = headers133+ self._poolmanager = _poolmanager134 135 # Pre-request hook.136 r = dispatch_hook('pre_request', hooks, self)137 self.__dict__.update(r.__dict__)2 unmodified lines140 def __repr__(self):141 return '<Request [%s]>' % (self.method)142 143 134- def _get_opener(self):135- """Creates appropriate opener object for urllib2."""136-137- _handlers = []138-139- if self.cookies is not None:140- _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))141-142- if self.proxies:143- _handlers.append(urllib2.ProxyHandler(self.proxies))144-145- _handlers.append(HTTPRedirectHandler)146-147- if not _handlers:148- return urllib2.urlopen149-150- if self.data or self.files:151- _handlers.extend(get_handlers())152-153- opener = urllib2.build_opener(*_handlers)154-155- 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))163-164- return opener.open165-166-144 def _build_response(self, resp, is_error=False):145 """Build internal :class:`Response <Response>` object146 from given response.147 """1 unmodified line149 150 def build(resp):151 152 response = Response()153+154+ # Pass settings over.155 response.config = self.config177- response.status_code = getattr(resp, 'code', None)156 179- try:180- response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))181- response.raw = resp157+ if resp:158 183- 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)161 162+ # Make headers case-insensitive.163+ response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))164 187- except AttributeError:188- pass165+ # Start off with our local cookies.166+ cookies = self.cookies or dict()167 168+ # Add new cookies from the server.169+ if 'set-cookie' in response.headers:170+ cookie_header = response.headers['set-cookie']171+172+ c = SimpleCookie()173+ c.load(cookie_header)174+175+ for k,v in c.items():176+ cookies.update({k: v.value})177+178+ # Save cookies in Response.179+ response.cookies = cookies180+181+ # Save original resopnse for later.182+ response.raw = resp183+184 if is_error:185 response.error = resp186 193- response.url = getattr(resp, 'url', None)187+ response.url = self._build_url()188 189 return response190 191 192 history = []193 194 r = build(resp)195+ cookies = self.cookies196+ self.cookies.update(r.cookies)197 198 if r.status_code in REDIRECT_STATI and not self.redirect:199 200 while (201 ('location' in r.headers) and202 ((r.status_code is codes.see_other) or (self.allow_redirects))203 ):204 209- r.raw.close()210-205 if not len(history) < self.config.get('max_redirects'):206 raise TooManyRedirects()207 208 history.append(r)15 unmodified lines224 method = 'GET'225 else:226 method = self.method227 228+ # Remove the cookie headers that were sent.229+ headers = self.headers230+ try:231+ del headers['Cookie']232+ except KeyError:233+ pass234+235 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 )247+248 request.send()249+ cookies.update(request.response.cookies)250 r = request.response251+ self.cookies.update(r.cookies)252 253 r.history = history254 255 self.response = r256 self.response.request = self257+ self.response.cookies.update(self.cookies)258 259 260 @staticmethod261 def _encode_params(data):6 unmodified lines268 Otherwise, assumes the data is already encoded appropriately, and269 returns it twice.270 """271 272+ if hasattr(data, '__iter__'):273+ data = dict(data)274+275 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 lines285 286 def _build_url(self):287 """Build the actual URL to use."""288 289+ if not self.url:290+ raise URLRequired()291+292 # Support for unicode domain names and paths.293 scheme, netloc, path, params, query, fragment = urlparse(self.url)294+295+ if not scheme:296+ raise ValueError()297+298 netloc = netloc.encode('idna')299+300 if isinstance(path, unicode):301 path = path.encode('utf-8')302+303 path = urllib.quote(urllib.unquote(path))304 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))305 306 if self._enc_params:4 unmodified lines311 else:312 return self.url313 314 298- 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 lines322 :param anyway: If True, request will be sent, even if it has323 already been sent.324 """325 309- # Some people...310- if not self.url:311- raise URLRequired312-326 # Logging327 if self.config.get('verbose'):328 self.config.get('verbose').write('%s %s %s\n' % (329 datetime.now().isoformat(), self.method, self.url1 unmodified line331 332 # Build the URL333 url = self._build_url()334 322- # Attach uploaded files.335+ # Nottin' on you.336+ body = None337+ content_type = None338+339+ # Multi-part file uploads.340 if self.files:324- register_openers()341+ if not isinstance(self.data, basestring):342 326- # Add form-data to the multipart.343+ try:344+ fields = self.data.copy()345+ except AttributeError:346+ fields = dict(self.data)347+348+ 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)356 330- 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'362 332- 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_type366 367+368 if self.auth:369 auth_func, auth_args = self.auth370 371+ # Allow auth to make its changes.372 r = auth_func(self, *auth_args)373 374+ # Update self to reflect the auth changes.375 self.__dict__.update(r.__dict__)376 343- # 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)379 346- # 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)388 389 if not self.sent or anyway:390 353- try:354- opener = self._get_opener()355- try:391+ if self.cookies:392 357- resp = opener(req, timeout=self.timeout)393+ # Skip if 'cookie' header is explicitly set.394+ if 'cookie' not in self.headers:395 359- 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] = v400 364- 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()403 369- resp = opener(req)404+ # Attach Cookie header to request.405+ self.headers['Cookie'] = cookie_header406 371- if self.config.get('timeout_fallback'):372- # restore global timeout373- socket.setdefaulttimeout(old_timeout)407+ try:408+ # Send the request.409 375- 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+ )422 378- 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)423 385- 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 = None429 387- 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.')433 434+ self._build_response(r)435 392- self.sent = self.response.ok436+ # Response manipulation hook.437+ self.response = dispatch_hook('response', self.hooks, self.response)438 394- # 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__)442 397- # 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 = True446 401- return self.sent447+ return self.sent448 449 450 class Response(object):451 """The core :class:`Response <Response>` object. All20 unmodified lines472 473 #: Final URL location of Response.474 self.url = None475 430- #: True if no :attr:`error` occurred.431- self.ok = False432-476 #: Resulting :class:`HTTPError` of request, if one occurred.477 self.error = None478 479 #: A list of :class:`Response <Response>` objects from4 unmodified lines484 #: The :class:`Request <Request>` that created the Response.485 self.request = None486 487 #: A dictionary of Cookies the server sent back.445- self.cookies = None488+ self.cookies = {}489 490 #: Dictionary of configurations for this request.448- self.config = None491+ self.config = {}492 493 494 def __repr__(self):495 return '<Response [%s]>' % (self.status_code)496 454-497 def __nonzero__(self):498 """Returns true if :attr:`status_code` is 'OK'."""499+ return self.ok500 458- return not self.error501+ @property502+ def ok(self):503+ try:504+ self.raise_for_status()505+ except HTTPError:506+ return False507+ return True508 509+510 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+ )520 521 def generate():522 while 1:523 chunk = self.raw.read(chunk_size)524 if not chunk:525 break526 yield chunk527 self._content_consumed = True528+529 gen = generate()530+531 if 'gzip' in self.headers.get('content-encoding', ''):532 gen = stream_decode_gzip(gen)533+534 if decode_unicode is None:535 decode_unicode = self.config.get('decode_unicode')536+537 if decode_unicode:538 gen = stream_decode_response_unicode(gen, self)539+540 return gen541 542+543 @property544 def content(self):545 """Content of the response, in bytes or unicode546 (if available).29 unmodified lines576 577 578 def raise_for_status(self):579 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""580+581 if self.error:582 raise self.error583 584+ if (self.status_code >= 300) and (self.status_code < 400):585+ raise HTTPError('%s Redirection' % self.status_code)586+587+ elif (self.status_code >= 400) and (self.status_code < 500):588+ raise HTTPError('%s Client Error' % self.status_code)589+590+ elif (self.status_code >= 500) and (self.status_code < 600):591+ raise HTTPError('%s Server Error' % self.status_code)592+593+modified:requests/sessions.py+53 added-27 removed
7 unmodified lines8 requests (cookies, auth, proxies).9 10 """11 12-import cookielib13-12 from .defaults import defaults13 from .models import Request14 from .hooks import dispatch_hook17-from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand15+from .utils import header_expand16+from .packages.urllib3.poolmanager import PoolManager17 18 19 def merge_kwargs(local_kwarg, default_kwarg):20 """Merges kwarg dictionaries.41 unmodified lines62 timeout=None,63 proxies=None,64 hooks=None,65 params=None,67- config=None,68- keep_alive=True):66+ config=None):67 68 self.headers = headers or {}69 self.cookies = cookies or {}70 self.auth = auth1 unmodified line72 self.proxies = proxies or {}73 self.hooks = hooks or {}74 self.params = params or {}75 self.config = config or {}78- self.keep_alive = keep_alive76 77 for (k, v) in defaults.items():78 self.config.setdefault(k, v)79 80+ self.poolmanager = PoolManager(81+ num_pools=self.config.get('pool_connections'),82+ maxsize=self.config.get('pool_maxsize')83+ )84+85 # Set up a CookieJar to be used by default84- self.cookies = cookielib.FileCookieJar()86+ self.cookies = {}87 88+ # Add passed cookies in.89+ if cookies is not None:90+ self.cookies.update(cookies)91+92 def __repr__(self):93 return '<requests-client at 0x%x>' % (id(self))94 95 def __enter__(self):13 unmodified lines109 allow_redirects=False,110 proxies=None,111 hooks=None,112 return_response=True,107- config=None):113+ config=None,114+ prefetch=False):115 116 """Constructs and sends a :class:`Request <Request>`.117 Returns :class:`Response <Response>` object.118 9 unmodified lines128 :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 """134 135 method = str(method).upper()136 129- 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 params143 132- if isinstance(cookies, dict):133- cookies = add_dict_to_cookiejar(self.cookies, cookies)134-135- cookies = cookiejar_from_dict(cookies)136-137- # 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 lines158 hooks=hooks,159 timeout=timeout,160 allow_redirects=allow_redirects,161 proxies=proxies,155- config=config162+ config=config,163+ _poolmanager=self.poolmanager164 )165 166+ # 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)170 171 args[attr] = merge_kwargs(local_val, session_val)172 164-173 # Arguments manipulation hook.174 args = dispatch_hook('args', args['hooks'], args)175 176+ # Create the (empty) response.177 r = Request(**args)178 179+ # Give the response some context.180+ r.session = self181+182 # Don't send if asked nicely.183 if not return_response:184 return r185 186 # Send the HTTP Request.175- r.send()187+ r.send(prefetch=prefetch)188 189+ # Send any cookies back up the to the session.190+ self.cookies.update(r.response.cookies)191+192+ # Return the response.193 return r.response194 195 196 def get(self, url, **kwargs):3 unmodified lines200 :param **kwargs: Optional arguments that ``request`` takes.201 """202 203 kwargs.setdefault('allow_redirects', True)188- return self.request('GET', url, **kwargs)204+ return self.request('get', url, **kwargs)205 206 207+ def options(self, url, **kwargs):208+ """Sends a OPTIONS request. Returns :class:`Response` object.209+210+ :param url: URL for the new :class:`Request` object.211+ :param **kwargs: Optional arguments that ``request`` takes.212+ """213+214+ kwargs.setdefault('allow_redirects', True)215+ return self.request('options', url, **kwargs)216+217+218 def head(self, url, **kwargs):219 """Sends a HEAD request. Returns :class:`Response` object.220 221 :param url: URL for the new :class:`Request` object.222 :param **kwargs: Optional arguments that ``request`` takes.223 """224 225 kwargs.setdefault('allow_redirects', True)199- return self.request('HEAD', url, **kwargs)226+ return self.request('head', url, **kwargs)227 228 202- def post(self, url, data='', **kwargs):229+ def post(self, url, data=None, **kwargs):230 """Sends a POST request. Returns :class:`Response` object.231 232 :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 lines236 237 return self.request('post', url, data=data, **kwargs)238 239 213- def put(self, url, data='', **kwargs):240+ def put(self, url, data=None, **kwargs):241 """Sends a PUT request. Returns :class:`Response` object.242 243 :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 lines247 248 return self.request('put', url, data=data, **kwargs)249 250 224- def patch(self, url, data='', **kwargs):251+ def patch(self, url, data=None, **kwargs):252 """Sends a PATCH request. Returns :class:`Response` object.253 254 :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 """258 232- return self.request('patch', url, data='', **kwargs)259+ return self.request('patch', url, data=data, **kwargs)260 261 262 def delete(self, url, **kwargs):263 """Sends a DELETE request. Returns :class:`Response` object.4 unmodified lines268 269 return self.request('delete', url, **kwargs)270 271 245-272 def session(**kwargs):273 """Returns a :class:`Session` for context-management."""274 249- return Session(**kwargs)275+ return Session(**kwargs)modified:requests/structures.py+1 added
6 unmodified lines7 Data structures that power Requests.8 9 """10 11+12 class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary14 15 For example, ``headers['content-encoding']`` will return the51 unmodified linesmodified:AUTHORS+4 added-1 removed
47 unmodified lines48 - Fredrik Möllerstrand49 - Daniel Hengeveld50 - Dan Head51 - Bruno Renié52-- David Fischer52+- David Fischer53+- Joseph McCullough54+- Juergen Brendel55+- Juan Riazamodified:HISTORY.rst+14 added
1 History2 -------3 4+5+0.8.0 (2011-11-09)6+++++++++++++++++++7+8+* Keep-alive support!9+* Complete removal of Urllib210+* Complete removal of Poster11+* Complete removal of CookieJars12+* New ConnectionError raising13+* Safe_mode for error catching14+* prefetch parameter for request methods15+* OPTION method16+* Async pool size throttling17+18 0.7.6 (2011-11-07)19 ++++++++++++++++++20 21 * Digest authentication bugfix (attach query data to path)234 unmodified linesmodified:README.rst+1 added-1 removed
25 unmodified lines26 27 Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,28 **PATCH**, and **DELETE** HTTP requests. You can add headers, form data,29 multipart files, and parameters with simple Python dictionaries, and access the30-response data in the same way. It's powered by urllib2, but it does30+response data in the same way. It's powered by httplib, but it does31 all the hard work and crazy hacks for you.32 33 34 Features68 unmodified linesmodified:setup.py+1 added-1 removed
35 unmodified lines36 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 linesmodified:test_requests.py+64 added-45 removed
2 unmodified lines3 4 from __future__ import with_statement5 6 import time7-import cookielib7 import os8 import unittest9 10 import requests11 import envoy13-from urllib2 import HTTPError12+from requests import HTTPError13 14 try:15 import omnijson as json16 except ImportError:39 unmodified lines56 57 def tearDown(self):58 """Teardown."""59 # self.httpbin.kill()60+ pass61 62+63 def test_entry_points(self):63- import requests64 65 requests.session66 requests.session().get67 requests.session().head166 unmodified lines234 235 for service in SERVICES:236 237 r = requests.get(service('status', '404'))238+ # print r.status_code239+ # r.raise_for_status()240 self.assertEqual(r.ok, False)241 242 243 def test_status_raising(self):4 unmodified lines248 self.assertFalse(r.error)249 r.raise_for_status()250 251 250- def test_cookie_jar(self):251-252- jar = cookielib.CookieJar()253- self.assertFalse(jar)254-255- url = httpbin('cookies', 'set', 'requests_cookie', 'awesome')256- r = requests.get(url, cookies=jar)257- self.assertTrue(jar)258-259- 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)265-266- r = requests.get(httpbin('cookies'), cookies=jar)267- self.assertTrue('awesome' in r.content)268-269-252 def test_decompress_gzip(self):253 254 r = requests.get(httpbin('gzip'))255 r.content.decode('ascii')49 unmodified lines305 306 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')311 312 313 def test_urlencoded_post_querystring(self):10 unmodified lines324 self.assertEquals(rbody.get('form'), {}) # No form supplied325 self.assertEquals(rbody.get('data'), '')326 327 346- def test_nonurlencoded_post_querystring(self):347-348- for service in SERVICES:349-350- r = requests.post(service('post'), params='fooaowpeuf')351-352- self.assertEquals(r.status_code, 200)353- self.assertEquals(r.headers['content-type'], 'application/json')354- self.assertEquals(r.url, service('post?fooaowpeuf'))355-356- rbody = json.loads(r.content)357- self.assertEquals(rbody.get('form'), {}) # No form supplied358- self.assertEquals(rbody.get('data'), '')359-360-328 def test_urlencoded_post_query_and_data(self):329 330 for service in SERVICES:331 10 unmodified lines342 self.assertEquals(rbody.get('form'), dict(test2='foobar'))343 self.assertEquals(rbody.get('data'), '')344 345 379- def test_nonurlencoded_post_query_and_data(self):346+ def test_nonurlencoded_postdata(self):347 348 for service in SERVICES:349 383- r = requests.post(service('post'),384- params='fooaowpeuf', data="foobar")350+ r = requests.post(service('post'), data="foobar")351 352 self.assertEquals(r.status_code, 200)353 self.assertEquals(r.headers['content-type'], 'application/json')388- self.assertEquals(r.url, service('post?fooaowpeuf'))354 355 rbody = json.loads(r.content)356 392- self.assertEquals(rbody.get('form'), None)357+ self.assertEquals(rbody.get('form'), {})358 self.assertEquals(rbody.get('data'), 'foobar')359 360 361 # def test_idna(self):103 unmodified lines465 assert new_heads['User-agent'] in r3.content466 467 self.assertEqual(r2.status_code, 200)468 469+ def test_session_persistent_cookies(self):470 471+ s = requests.session()472+473+ # 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'))477+478+ # Those cookies persist transparently.479+ c = json.loads(r.content).get('cookies')480+ assert c == _c481+482+ # Double check.483+ r = s.get(httpbin('cookies'), cookies={})484+ c = json.loads(r.content).get('cookies')485+ assert c == _c486+487+ # 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 == _c492+493+ # 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 == _c498+499+ # 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')502+503+ assert 'k' in c504+505+ # And server-set cookie persistience.506+ r = s.get(httpbin('cookies'))507+ c = json.loads(r.content).get('cookies')508+509+ assert 'k' in c510+511+512+513 def test_session_persistent_params(self):514 515 params = {'a': 'a_test'}516 20 unmodified lines537 assert params3['b'] in r3.content538 assert params3['c'] in r3.content539 540 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 False550 534- r = requests.get('http://somedomainthatclearlydoesntexistg.com')551+552+ config = {'safe_mode': True}553+ r = requests.get(hah, allow_redirects=False, config=config)554 assert r.content == None555 556 557 if __name__ == '__main__':1 unmodified line