Merge branch 'develop'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 72943d0, 9aa62d5 · Browse files · 37 files·+2173 added−1022 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
37 files+2173 added−1022 removed
- other:+2173 added−1022 removed
Provenance
- Commit
6e9cb09- Tree
f39305c- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
72943d0- Parent 2
9aa62d5
37 files changed+2173 added−1022 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/__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+131 added
1+# urllib3/_collections.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+from collections import deque8+9+from threading import RLock10+11+__all__ = ['RecentlyUsedContainer']12+13+14+class AccessEntry(object):15+ __slots__ = ('key', 'is_valid')16+17+ def __init__(self, key, is_valid=True):18+ self.key = key19+ self.is_valid = is_valid20+21+22+class RecentlyUsedContainer(dict):23+ """24+ Provides a dict-like that maintains up to ``maxsize`` keys while throwing25+ away the least-recently-used keys beyond ``maxsize``.26+ """27+28+ # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we29+ # will attempt to cleanup the invalidated entries in the access_log30+ # datastructure during the next 'get' operation.31+ CLEANUP_FACTOR = 1032+33+ def __init__(self, maxsize=10):34+ self._maxsize = maxsize35+36+ self._container = {}37+38+ # We use a deque to to store our keys ordered by the last access.39+ self.access_log = deque()40+ self.access_log_lock = RLock()41+42+ # We look up the access log entry by the key to invalidate it so we can43+ # insert a new authorative entry at the head without having to dig and44+ # find the old entry for removal immediately.45+ self.access_lookup = {}46+47+ # Trigger a heap cleanup when we get past this size48+ self.access_log_limit = maxsize * self.CLEANUP_FACTOR49+50+ def _invalidate_entry(self, key):51+ "If exists: Invalidate old entry and return it."52+ old_entry = self.access_lookup.get(key)53+ if old_entry:54+ old_entry.is_valid = False55+56+ return old_entry57+58+ def _push_entry(self, key):59+ "Push entry onto our access log, invalidate the old entry if exists."60+ self._invalidate_entry(key)61+62+ new_entry = AccessEntry(key)63+ self.access_lookup[key] = new_entry64+65+ self.access_log_lock.acquire()66+ self.access_log.appendleft(new_entry)67+ self.access_log_lock.release()68+69+ def _prune_entries(self, num):70+ "Pop entries from our access log until we popped ``num`` valid ones."71+ while num > 0:72+ self.access_log_lock.acquire()73+ p = self.access_log.pop()74+ self.access_log_lock.release()75+76+ if not p.is_valid:77+ continue # Invalidated entry, skip78+79+ dict.pop(self, p.key, None)80+ self.access_lookup.pop(p.key, None)81+ num -= 182+83+ def _prune_invalidated_entries(self):84+ "Rebuild our access_log without the invalidated entries."85+ self.access_log_lock.acquire()86+ self.access_log = deque(e for e in self.access_log if e.is_valid)87+ self.access_log_lock.release()88+89+ def _get_ordered_access_keys(self):90+ "Return ordered access keys for inspection. Used for testing."91+ self.access_log_lock.acquire()92+ r = [e.key for e in self.access_log if e.is_valid]93+ self.access_log_lock.release()94+95+ return r96+97+ def __getitem__(self, key):98+ item = dict.get(self, key)99+100+ if not item:101+ raise KeyError(key)102+103+ # Insert new entry with new high priority, also implicitly invalidates104+ # the old entry.105+ self._push_entry(key)106+107+ if len(self.access_log) > self.access_log_limit:108+ # Heap is getting too big, try to clean up any tailing invalidated109+ # entries.110+ self._prune_invalidated_entries()111+112+ return item113+114+ def __setitem__(self, key, item):115+ # Add item to our container and access log116+ dict.__setitem__(self, key, item)117+ self._push_entry(key)118+119+ # Discard invalid and excess entries120+ self._prune_entries(len(self) - self._maxsize)121+122+ def __delitem__(self, key):123+ self._invalidate_entry(key)124+ self.access_lookup.pop(key, None)125+ dict.__delitem__(self, key)126+127+ def get(self, key, default=None):128+ try:129+ return self[key]130+ except KeyError:131+ return defaultadded: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 %f 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+193 added-127 removed
1-1 # -*- coding: utf-8 -*-2 3 """4 requests.models5 ~~~~~~~~~~~~~~~6 7+This module contains the primary objects that power Requests.8 """9 10 import urllib11-import urllib212-import socket11 import zlib12 13+from Cookie import SimpleCookie14 from urlparse import urlparse, urlunparse, urljoin15 from datetime import datetime16 17 from .auth import dispatch as auth_dispatch18 from .hooks import dispatch_hook19 from .structures import CaseInsensitiveDict21-from .packages.poster.encode import multipart_encode22-from .packages.poster.streaminghttp import register_openers, get_handlers20 from .status_codes import codes24-from .exceptions import Timeout, URLRequired, TooManyRedirects25-from .monkeys import Request as _Request26-from .monkeys import HTTPRedirectHandler21+from .packages.urllib3.exceptions import MaxRetryError22+from .packages.urllib3.exceptions import SSLError as _SSLError23+from .packages.urllib3.exceptions import HTTPError as _HTTPError24+from .packages.urllib3 import connectionpool, poolmanager25+from .packages.urllib3.filepost import encode_multipart_formdata26+from .exceptions import (27+ Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28 from .utils import (28- dict_from_cookiejar, get_unicode_from_response,29- stream_decode_response_unicode, decode_gzip, stream_decode_gzip)29+ get_unicode_from_response, stream_decode_response_unicode,30+ decode_gzip, stream_decode_gzip, guess_filename)31 32 33 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)34 17 unmodified lines52 redirect=False,53 allow_redirects=False,54 proxies=None,55 hooks=None,55- config=None):56+ config=None,57+ _poolmanager=None):58 59 #: Float describes the timeout of the request.60 # (Use socket.setdefaulttimeout() as fallback)61 self.timeout = timeout1 unmodified line63 #: Request URL.64 self.url = url65 66 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.65- self.headers = headers67+ self.headers = dict(headers or [])68 69 #: Dictionary of files to multipart upload (``{filename: content}``).70 self.files = files71 6 unmodified lines78 79 #: Dictionary or byte of querystring data to attach to the80 #: :class:`Request <Request>`.81 self.params = None82+ self.params = dict(params or [])83 84 #: True if :class:`Request <Request>` is part of a redirect chain (disables history85 #: and HTTPError storage).86 self.redirect = redirect1 unmodified line88 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)89 self.allow_redirects = allow_redirects90 91 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})89- self.proxies = proxies92+ self.proxies = dict(proxies or [])93 94 self.data, self._enc_data = self._encode_params(data)95 self.params, self._enc_params = self._encode_params(params)96 5 unmodified lines102 self._auth = auth103 self.auth = auth_dispatch(auth)104 105 #: CookieJar to attach to :class:`Request <Request>`.103- self.cookies = cookies106+ self.cookies = dict(cookies or [])107 108 #: Dictionary of configurations for this request.106- self.config = config109+ self.config = dict(config or [])110 111 #: True if Request has been sent.112 self.sent = False113 114 #: Event-handling hooks.115 self.hooks = hooks116 117+ #: Session.118+ self.session = None119+120 if headers:121 headers = CaseInsensitiveDict(self.headers)122 else:123 headers = CaseInsensitiveDict()2 unmodified lines126 if k not in headers:127 headers[k] = v128 129 self.headers = headers130+ self._poolmanager = _poolmanager131 132 # Pre-request hook.133 r = dispatch_hook('pre_request', hooks, self)134 self.__dict__.update(r.__dict__)2 unmodified lines137 def __repr__(self):138 return '<Request [%s]>' % (self.method)139 140 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-141 def _build_response(self, resp, is_error=False):142 """Build internal :class:`Response <Response>` object143 from given response.144 """1 unmodified line146 147 def build(resp):148 149 response = Response()150+151+ # Pass settings over.152 response.config = self.config177- response.status_code = getattr(resp, 'code', None)153 179- try:180- response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))181- response.raw = resp154+ if resp:155 183- if self.cookies:184- response.cookies = dict_from_cookiejar(self.cookies)156+ # Fallback to None if there's no staus_code, for whatever reason.157+ response.status_code = getattr(resp, 'status', None)158 159+ # Make headers case-insensitive.160+ response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))161 187- except AttributeError:188- pass162+ # Start off with our local cookies.163+ cookies = self.cookies or dict()164 165+ # Add new cookies from the server.166+ if 'set-cookie' in response.headers:167+ cookie_header = response.headers['set-cookie']168+169+ c = SimpleCookie()170+ c.load(cookie_header)171+172+ for k,v in c.items():173+ cookies.update({k: v.value})174+175+ # Save cookies in Response.176+ response.cookies = cookies177+178+ # Save original resopnse for later.179+ response.raw = resp180+181 if is_error:182 response.error = resp183 193- response.url = getattr(resp, 'url', None)184+ response.url = self._build_url()185 186 return response187 188 189 history = []190 191 r = build(resp)192+ cookies = self.cookies193+ self.cookies.update(r.cookies)194 195 if r.status_code in REDIRECT_STATI and not self.redirect:196 197 while (198 ('location' in r.headers) and199 ((r.status_code is codes.see_other) or (self.allow_redirects))200 ):201 209- r.raw.close()210-202 if not len(history) < self.config.get('max_redirects'):203 raise TooManyRedirects()204 205 history.append(r)15 unmodified lines221 method = 'GET'222 else:223 method = self.method224 225+ # Remove the cookie headers that were sent.226+ headers = self.headers227+ try:228+ del headers['Cookie']229+ except KeyError:230+ pass231+232 request = Request(233 url=url,236- headers=self.headers,234+ headers=headers,235 files=self.files,236 method=method,239- # data=self.data,240- # params=self.params,237+ params=self.session.params,238 auth=self._auth,242- cookies=self.cookies,239+ cookies=cookies,240 redirect=True,244- config=self.config241+ config=self.config,242+ _poolmanager=self._poolmanager243 )244+245 request.send()246+ cookies.update(request.response.cookies)247 r = request.response248+ self.cookies.update(r.cookies)249 250 r.history = history251 252 self.response = r253 self.response.request = self254+ self.response.cookies.update(self.cookies)255 256 257 @staticmethod258 def _encode_params(data):6 unmodified lines265 Otherwise, assumes the data is already encoded appropriately, and266 returns it twice.267 """268 269+ if hasattr(data, '__iter__'):270+ data = dict(data)271+272 if hasattr(data, 'items'):273 result = []274 for k, vs in data.items():275 for v in isinstance(vs, list) and vs or [vs]:6 unmodified lines282 283 def _build_url(self):284 """Build the actual URL to use."""285 286+ if not self.url:287+ raise URLRequired()288+289 # Support for unicode domain names and paths.290 scheme, netloc, path, params, query, fragment = urlparse(self.url)291+292+ if not scheme:293+ raise ValueError()294+295 netloc = netloc.encode('idna')296+297 if isinstance(path, unicode):298 path = path.encode('utf-8')299+300 path = urllib.quote(urllib.unquote(path))301 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))302 303 if self._enc_params:4 unmodified lines308 else:309 return self.url310 311 298- def send(self, anyway=False):312+ def send(self, anyway=False, prefetch=False):313 """Sends the request. Returns True of successful, false if not.314 If there was an HTTPError during transmission,315 self.response.status_code will contain the HTTPError code.316 2 unmodified lines319 :param anyway: If True, request will be sent, even if it has320 already been sent.321 """322 309- # Some people...310- if not self.url:311- raise URLRequired312-323 # Logging324 if self.config.get('verbose'):325 self.config.get('verbose').write('%s %s %s\n' % (326 datetime.now().isoformat(), self.method, self.url1 unmodified line328 329 # Build the URL330 url = self._build_url()331 322- # Attach uploaded files.332+ # Nottin' on you.333+ body = None334+ content_type = None335+336+ # Multi-part file uploads.337 if self.files:324- register_openers()338+ if not isinstance(self.data, basestring):339 326- # Add form-data to the multipart.327- if self.data:328- self.files.update(self.data)340+ try:341+ fields = self.data.copy()342+ except AttributeError:343+ fields = dict(self.data)344 330- data, headers = multipart_encode(self.files)345+ for (k, v) in self.files.items():346+ fields.update({k: (guess_filename(k) or k, v.read())})347 348+ (body, content_type) = encode_multipart_formdata(fields)349+ else:350+ pass351+ # TODO: Conflict?352 else:333- data = self._enc_data334- headers = {}353+ if self.data:354 355+ body = self._enc_data356+ if isinstance(self.data, basestring):357+ content_type = None358+ else:359+ content_type = 'application/x-www-form-urlencoded'360+361+ # Add content-type if it wasn't explicitly provided.362+ if (content_type) and (not 'content-type' in self.headers):363+ self.headers['Content-Type'] = content_type364+365+366 if self.auth:367 auth_func, auth_args = self.auth368 369+ # Allow auth to make its changes.370 r = auth_func(self, *auth_args)371 372+ # Update self to reflect the auth changes.373 self.__dict__.update(r.__dict__)374 343- # Build the Urllib2 Request.344- req = _Request(url, data=data, headers=headers, method=self.method)375+ _p = urlparse(url)376+ proxy = self.proxies.get(_p.scheme)377 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)378+ if proxy:379+ conn = poolmanager.proxy_from_url(url)380+ else:381+ # Check to see if keep_alive is allowed.382+ if self.config.get('keep_alive'):383+ conn = self._poolmanager.connection_from_url(url)384+ else:385+ conn = connectionpool.connection_from_url(url)386 387 if not self.sent or anyway:388 353- try:354- opener = self._get_opener()355- try:389+ if self.cookies:390 357- resp = opener(req, timeout=self.timeout)391+ # Skip if 'cookie' header is explicitly set.392+ if 'cookie' not in self.headers:393 359- except TypeError, err:360- # timeout argument is new since Python v2.6361- if not 'timeout' in str(err):362- raise394+ # Simple cookie with our dict.395+ c = SimpleCookie()396+ for (k, v) in self.cookies.items():397+ c[k] = v398 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)399+ # Turn it into a header.400+ cookie_header = c.output(header='').strip()401 369- resp = opener(req)402+ # Attach Cookie header to request.403+ self.headers['Cookie'] = cookie_header404 371- if self.config.get('timeout_fallback'):372- # restore global timeout373- socket.setdefaulttimeout(old_timeout)405+ try:406+ # Send the request.407 375- if self.cookies is not None:376- self.cookies.extract_cookies(resp, req)408+ r = conn.urlopen(409+ method=self.method,410+ url=url,411+ body=body,412+ headers=self.headers,413+ redirect=False,414+ assert_same_host=False,415+ preload_content=prefetch,416+ decode_content=False,417+ retries=self.config.get('max_retries', 0),418+ timeout=self.timeout,419+ )420 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)421 385- self._build_response(why, is_error=True)422+ except MaxRetryError, e:423+ if not self.config.get('safe_mode', False):424+ raise ConnectionError(e)425+ else:426+ r = None427 387- else:388- self._build_response(resp)389- self.response.ok = True428+ except (_SSLError, _HTTPError), e:429+ if not self.config.get('safe_mode', False):430+ raise Timeout('Request timed out.')431 432+ self._build_response(r)433 392- self.sent = self.response.ok434+ # Response manipulation hook.435+ self.response = dispatch_hook('response', self.hooks, self.response)436 394- # Response manipulation hook.395- self.response = dispatch_hook('response', self.hooks, self.response)437+ # Post-request hook.438+ r = dispatch_hook('post_request', self.hooks, self)439+ self.__dict__.update(r.__dict__)440 397- # Post-request hook.398- r = dispatch_hook('post_request', self.hooks, self)399- self.__dict__.update(r.__dict__)441+ # If prefetch is True, mark content as consumed.442+ if prefetch:443+ self.response._content_consumed = True444 401- return self.sent445+ return self.sent446 447 448 class Response(object):449 """The core :class:`Response <Response>` object. All20 unmodified lines470 471 #: Final URL location of Response.472 self.url = None473 430- #: True if no :attr:`error` occurred.431- self.ok = False432-474 #: Resulting :class:`HTTPError` of request, if one occurred.475 self.error = None476 477 #: A list of :class:`Response <Response>` objects from4 unmodified lines482 #: The :class:`Request <Request>` that created the Response.483 self.request = None484 485 #: A dictionary of Cookies the server sent back.445- self.cookies = None486+ self.cookies = {}487 488 #: Dictionary of configurations for this request.448- self.config = None489+ self.config = {}490 491 492 def __repr__(self):493 return '<Response [%s]>' % (self.status_code)494 454-495 def __nonzero__(self):496 """Returns true if :attr:`status_code` is 'OK'."""497+ return self.ok498 458- return not self.error499+ @property500+ def ok(self):501+ try:502+ self.raise_for_status()503+ except HTTPError:504+ return False505+ return True506 507+508 def iter_content(self, chunk_size=10 * 1024, decode_unicode=None):509 """Iterates over the response data. This avoids reading the content510 at once into memory for large responses. The chunk size is the number511 of bytes it should read into memory. This is not necessarily the512 length of each item returned as decoding can take place.513 """514 if self._content_consumed:467- raise RuntimeError('The content for this response was '468- 'already consumed')515+ raise RuntimeError(516+ 'The content for this response was already consumed'517+ )518 519 def generate():520 while 1:521 chunk = self.raw.read(chunk_size)522 if not chunk:523 break524 yield chunk525 self._content_consumed = True526+527 gen = generate()528+529 if 'gzip' in self.headers.get('content-encoding', ''):530 gen = stream_decode_gzip(gen)531+532 if decode_unicode is None:533 decode_unicode = self.config.get('decode_unicode')534+535 if decode_unicode:536 gen = stream_decode_response_unicode(gen, self)537+538 return gen539 540+541 @property542 def content(self):543 """Content of the response, in bytes or unicode544 (if available).29 unmodified lines574 575 576 def raise_for_status(self):577 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""578+579 if self.error:580 raise self.error581 582+ if (self.status_code >= 300) and (self.status_code < 400):583+ raise HTTPError('%s Redirection' % self.status_code)584+585+ elif (self.status_code >= 400) and (self.status_code < 500):586+ raise HTTPError('%s Client Error' % self.status_code)587+588+ elif (self.status_code >= 500) and (self.status_code < 600):589+ raise HTTPError('%s Server Error' % self.status_code)590+591+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:requests/utils.py+6 added
18 unmodified lines19 20 from urllib2 import parse_http_list as _parse_list_header21 22 23+def guess_filename(obj):24+ """Tries to guess the filename of the given object."""25+ name = getattr(obj, 'name', None)26+ if name and name[0] != '<' and name[-1] != '>':27+ return name28+29 # From mitsuhiko/werkzeug (used with permission).30 def parse_list_header(value):31 """Parse lists as described by RFC 2068 Section 2.32 337 unmodified linesmodified:AUTHORS+10 added-1 removed
5 unmodified lines6 7 - Kenneth Reitz <me@kennethreitz.com>8 9 10+Urllib311+```````12+13+- Andrey Petrov <andrey.petrov@shazow.net>14+15+16 Patches and Suggestions17 ```````````````````````18 19 - Various Pocoo Members34 unmodified lines54 - Fredrik Möllerstrand55 - Daniel Hengeveld56 - Dan Head57 - Bruno Renié52-- David Fischer58+- David Fischer59+- Joseph McCullough60+- Juergen Brendel61+- Juan Riazamodified:HISTORY.rst+15 added
1 History2 -------3 4+5+0.8.0 (2011-11-13)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+* File uploads send real names18+19 0.7.6 (2011-11-07)20 ++++++++++++++++++21 22 * 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