Merge branch 'develop' into feature/rewrite
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 b908559, e257151 · Browse files · 43 files·+1424 added−916 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
43 files+1424 added−916 removed
- other:+1424 added−916 removed
Provenance
- Commit
95336a0- Tree
41e2700- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
b908559- Parent 2
e257151
43 files changed+1424 added−916 removed
deleted:debian/changelog-5 removed
1-python-requests (0.4.1-0) testing; urgency=low2-3- * Initial Debian package4-5- -- Bruno Clermont <bruno.clermont@gmail.com> Thu, 26 May 2011 16:25:00 -0500deleted:debian/compat-1 removed
1-5deleted:debian/control-13 removed
1-Source: python-requests2-Section: python3-Priority: optional4-Maintainer: Bruno Clermont <bruno.clermont@gmail.com>5-Homepage: https://github.com/bclermont/requests6-Bugs: https://github.com/bclermont/requests/issues7-Build-Depends: debhelper, python-support8-9-Package: python-requests10-Architecture: all11-Depends: ${python:Depends}, python-support12-Provides: ${python:Provides}13-Description: Python HTTP Requests for Humans.deleted:debian/docs-1 removed
1-docs/user/*.rstdeleted:debian/pyversions-1 removed
1-2.4-deleted:debian/rules-42 removed
1-#!/usr/bin/make -f2-3-# Verbose mode4-#export DH_VERBOSE=15-6-clean:7- dh_testdir8- dh_testroot9-10- rm -rf build requests.egg-info11-# find django-sentry/ -name *.pyc | xargs rm -f12-13- dh_clean14-15-build:16- dh_testdir17-18- python setup.py build19-20-install:21- dh_testdir22- dh_installdirs23-24- python setup.py install --root $(CURDIR)/debian/python-requests25-26-binary-indep: install27-28-binary-arch: install29- dh_install30- dh_installdocs31-# dh_installchangelogs32- dh_compress33- dh_fixperms34- dh_pysupport35- dh_gencontrol36- dh_installdeb37- dh_md5sums38- dh_builddeb -- -Z lzma -z939-40-binary: binary-indep binary-arch41-.PHONY: build clean binary-indep binary-arch binary42-modified:docs/community/faq.rst+1 added-1 removed
7 unmodified lines8 Encoded Data?9 -------------10 11 Requests automatically decompresses gzip-encoded responses, and does12-its best to decodes response content to unicode when possible.12+its best to decode response content to unicode when possible.13 14 You can get direct access to the raw response (and even the socket),15 if needed as well.16 67 unmodified linesadded:docs/community/out-there.rst+63 added
1+Modules2+=======3+4+- `requests-oauth-hook <https://github.com/maraujop/requests-oauth-hook>`_, 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.9+- `WhitespaceBot <https://github.com/Gunio/WhitespaceBot/>`_, a project that automatically forks repos, strips trailing whitespace, and sends a pull request.10+11+Articles & Talks12+================13+- `Python for the Web <http://gun.io/blog/python-for-the-web/>`_ teaches how to use Python to interact with the web, using Requests.14+- `Daniel Greenfield's Review of Requests <http://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_15+- `My 'Python for Humans' talk <http://python-for-humans.heroku.com>`_ ( `audio <http://codeconf.s3.amazonaws.com/2011/pycodeconf/talks/PyCodeConf2011%20-%20Kenneth%20Reitz.m4a>`_ )16+- `Issac Kelly's 'Consuming Web APIs' talk <http://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_17+- `Blog post about Requests via Yum <http://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_18+- `Russian blog post introducing Requests <http://habrahabr.ru/blogs/python/126262/>`_19+20+21+Integrations22+============23+24+ScraperWiki25+------------26+27+`ScraperWiki <https://scraperwiki.com/>`_ is an excellent service that allows28+you to run Python, Ruby, and PHP scraper scripts on the web. Now, Requests29+v0.6.1 is available to use in your scrapers!30+31+To give it a try, simply::32+33+ import requests34+35+36+Managed Packages37+================38+39+Requests is available in a number of popular package formats. Of course,40+the ideal way to install Requests is via The Cheeseshop.41+42+43+Ubuntu & Debian44+---------------45+46+Requests is available installed as a Debian package! Debian Etch Ubuntu, since Oneiric::47+48+ $ apt-get install python-requests49+50+Unfortunately, the most recent version available is v0.5.0. If you're on the51+Debian Python Package team, I'd love an update of that :)52+53+54+Fedora and RedHat55+-----------------56+57+You can easily install Requests v0.6.1 with yum on rpm-based systems::58+59+ $ yum install python-requests60+61+62+63+modified:docs/community/support.rst+1 added-1 removed
1 unmodified line2 3 Support4 =======5 6-If you have a questions or issues about Requests, there are serveral options:6+If you have a questions or issues about Requests, there are several options:7 8 Send a Tweet9 ------------10 27 unmodified linesmodified:docs/community/updates.rst+1 added-1 removed
2 unmodified lines3 Updates4 =======5 6 If you'd like to stay up to date on the community and development of Requests,7-there are serveral options:7+there are several options:8 9 GitHub10 ------11 19 unmodified linesmodified:docs/user/advanced.rst+75 added-7 removed
15 unmodified lines16 A session object has all the methods of the main Requests API.17 18 Let's persist some cookies across requests::19 20- with requests.session() as s:20+ s = requests.session()21 22- s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23- r = s.get("http://httpbin.org/cookies")22+ s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23+ r = s.get("http://httpbin.org/cookies")24 25- print r.content26- # '{"cookies": {"sessioncookie": "123456789"}}'25+ print r.content26+ # '{"cookies": {"sessioncookie": "123456789"}}'27 28 29 Sessions can also be used to provide default data to the request methods::30 7 unmodified lines38 39 40 .. admonition:: Global Settings41 42- Certain parameters are best set at the ``request.config`` level43- (e.g.. a global proxy, user agent header).42+ Certain parameters are best set in the ``config`` dictionary43+ (e.g. user agent header).44 45 46+Asynchronous Requests47+----------------------48+49+Requests has first-class support for non-blocking i/o requests, powered50+by gevent. This allows you to send a bunch of HTTP requests at the same51+52+First, let's import the async module. Heads up — if you don't have53+`gevent <gevent>`_ this will fail::54+55+ from requests import async56+57+The ``async`` module has the exact same api as ``requests``, except it58+doesn't send the request immediately. Instead, it returns the ``Request``59+object.60+61+We can build a list of ``Request`` objects easily::62+63+ urls = [64+ 'http://python-requests.org',65+ 'http://httpbin.org',66+ 'http://python-guide.org',67+ 'http://kennethreitz.com'68+ ]69+70+ rs = [async.get(u) for u in urls]71+72+Now we have a list of ``Request`` objects, ready to be sent. We could send them73+one at a time with ``Request.send()``, but that would take a while. Instead,74+we'll send them all at the same time with ``async.map()``. Using ``async.map()``75+will also guarantee execution of the ``response`` hook, described below. ::76+77+ >>> async.map(rs)78+ [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]79+80+81 Event Hooks82 -----------83 84 Requests has a hook system that you can use to manipulate portions of71 unmodified lines156 }157 }158 159 160+Custom Authentication161+---------------------162 163+Requests allows you to use specify your own authentication mechanism.164+165+When you pass our authentication tuple to a request method, the first166+string is the type of authentication. 'basic' is inferred if none is167+provided.168+169+You can pass in a callable object instead of a string for the first item170+in the tuple, and it will be used in place of the built in authentication171+callbacks.172+173+Let's pretend that we have a web service that will only respond if the174+``X-Pizza`` header is set to a password value. Unlikely, but just go with it.175+176+We simply need to define a callback function that will be used to update the177+Request object, right before it is dispatched.178+179+::180+181+ def pizza_auth(r, username):182+ """Attaches HTTP Pizza Authentication to the given Request object.183+ """184+ r.headers['X-Pizza'] = username185+186+ return r187+188+Then, we can make a request using our Pizza Auth::189+190+ >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))191+ <Response [200]>192+193+194 Verbose Logging195 ---------------196 197 If you want to get a good look at what HTTP requests are being sent8 unmodified linesmodified:docs/user/install.rst+23 added-1 removed
16 unmodified lines17 or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::18 19 $ easy_install requests20 21-But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21+But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install>`_.22 23 24 25 Cheeseshop Mirror27 unmodified lines53 Once you have a copy of the source, you can embed it in your Python package,54 or install it into your site-packages easily::55 56 $ python setup.py install57+58+.. _gevent:59+60+Installing Gevent61+-----------------62+63+If you are using the ``requests.async`` module for making concurrent64+requests, you need to install gevent.65+66+To install gevent, you'll need ``libevent``.67+68+OSX::69+70+ $ brew install libevent71+72+Ubuntu::73+74+ $ apt-get install libevent-dev75+76+Once you have ``libevent``, you can install ``gevent`` with ``pip``::77+78+ $ pip install geventmodified:docs/user/intro.rst-2 removed
45 unmodified lines46 Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.47 48 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.49 50-51-modified:docs/user/quickstart.rst+29 added
134 unmodified lines135 136 >>> r = requests.get(url, cookies=cookies)137 >>> r.content138 '{"cookies": {"cookies_are": "working"}}'139+140+141+Basic Authentication142+--------------------143+144+Most web services require authentication. There many different types of145+authentication, but the most common is called HTTP Basic Auth.146+147+Making requests with Basic Auth is easy, with Requests::148+149+ >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))150+ <Response [200]>151+152+153+Digest Authentication154+---------------------155+156+Another popular form of protecting web service is Digest Authentication.157+158+Requests supports it!::159+160+ >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'161+ >>> requests.get(url, auth=('digest', 'user', 'pass'))162+ <Response [200]>163+164+165+-----------------------166+167+Ready for more? Check out the advanced_ section.modified:docs/api.rst+15 added-3 removed
29 unmodified lines30 31 .. autoclass:: Response32 :inherited-members:33 34+Async35+-----36 37+.. module:: requests.async38 39+40+.. autofunction:: map41+.. autofunction:: request42+.. autofunction:: head43+.. autofunction:: get44+.. autofunction:: post45+.. autofunction:: put46+.. autofunction:: patch47+.. autofunction:: delete48+49+50+51 Utilities52 ---------53 54 These functions are used internally, but may be useful outside of7 unmodified lines62 .. autofunction:: dict_from_cookiejar63 .. autofunction:: cookiejar_from_dict64 .. autofunction:: add_dict_to_cookiejar65 51-Curl52-~~~~53-.. autofunction:: curl_from_request66 67 Encodings68 ~~~~~~~~~69 36 unmodified linesmodified:docs/index.rst+2 added
39 unmodified lines40 ------------41 42 `Twitter, Inc <http://twitter.com>`_,43 a U.S. Federal Institution,44+NIH, 45 `Readability <http://readability.com>`_, and46 `Work for Pie <http://workforpie.com>`_47 use Requests internally.48 38 unmodified lines87 .. toctree::88 :maxdepth: 289 90 community/faq91+ community/out-there.rst92 community/support93 community/updates94 95 API Documentation23 unmodified linesmodified:requests/__init__.py+31 added-2 removed
1 # -*- coding: utf-8 -*-2 3-from core import *4-from core import __version__3+# __4+# /__) _ _ _ _ _/ _5+# / ( (- (/ (/ (- _) / _)6+# /7+8+"""9+requests10+~~~~~~~~11+12+:copyright: (c) 2011 by Kenneth Reitz.13+:license: ISC, see LICENSE for more details.14+15+"""16+17+__title__ = 'requests'18+__version__ = '0.7.2'19+__build__ = 0x00070220+__author__ = 'Kenneth Reitz'21+__license__ = 'ISC'22+__copyright__ = 'Copyright 2011 Kenneth Reitz'23+24+25+from . import utils26+from .models import HTTPError, Request, Response27+from .api import request, get, head, post, patch, put, delete28+from .sessions import session29+from .status_codes import codes30+from .exceptions import (31+ RequestException, AuthenticationError, Timeout, URLRequired,32+ TooManyRedirects33+)modified:requests/api.py+30 added-114 removed
2 unmodified lines3 """4 requests.api5 ~~~~~~~~~~~~6 7-This module impliments the Requests API.7+This module implements the Requests API.8 9 :copyright: (c) 2011 by Kenneth Reitz.10 :license: ISC, see LICENSE for more details.11 12 """13 14-import config15-from .models import Request, Response, AuthObject16-from .status_codes import codes17-from .hooks import dispatch_hook18-from .utils import cookiejar_from_dict14+from .sessions import session15 20-from urlparse import urlparse21-16 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')17 18+19 def request(method, url,25- params=None, data=None, headers=None, cookies=None, files=None, auth=None,26- timeout=None, allow_redirects=False, proxies=None, hooks=None):20+ params=None,21+ data=None,22+ headers=None,23+ cookies=None,24+ files=None,25+ auth=None,26+ timeout=None,27+ allow_redirects=False,28+ proxies=None,29+ hooks=None,30+ return_response=True,31+ config=None):32 28- """Constructs and sends a :class:`Request <models.Request>`.29- Returns :class:`Response <models.Response>` object.30-31- :param method: method for the new :class:`Request` object.32- :param url: URL for the new :class:`Request` object.33- :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.34- :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.35- :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.36- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.37- :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.38- :param auth: (optional) AuthObject to enable Basic HTTP Auth.39- :param timeout: (optional) Float describing the timeout of the request.40- :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.41- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.42- """43-44- if cookies is None:45- cookies = {}46-47- cookies = cookiejar_from_dict(cookies)48-49- args = dict(50- method = method,51- url = url,52- data = data,53- params = params,54- headers = headers,55- cookiejar = cookies,56- files = files,57- auth = auth,58- timeout = timeout or config.settings.timeout,59- allow_redirects = allow_redirects,60- proxies = proxies or config.settings.proxies,33+ s = session()34+ return s.request(35+ method, url, params, data, headers, cookies, files, auth,36+ timeout, allow_redirects, proxies, hooks, return_response,37+ config38 )39 63- # Arguments manipulation hook.64- args = dispatch_hook('args', hooks, args)40 66- r = Request(**args)41 68- # Pre-request hook.69- r = dispatch_hook('pre_request', hooks, r)70-71- # Send the HTTP Request.72- r.send()73-74- # Post-request hook.75- r = dispatch_hook('post_request', hooks, r)76-77- # Response manipulation hook.78- r.response = dispatch_hook('response', hooks, r.response)79-80- return r.response81-82-42 def get(url, **kwargs):84-43 """Sends a GET request. Returns :class:`Response` object.44 45 :param url: URL for the new :class:`Request` object.88- :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.89- :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.90- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.91- :param auth: (optional) AuthObject to enable Basic HTTP Auth.92- :param timeout: (optional) Float describing the timeout of the request.93- :param allow_redirects: (optional) Boolean. Set to False to disable redirect following.94- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.46+ :param **kwargs: Optional arguments that ``request`` takes.47 """48 49 kwargs.setdefault('allow_redirects', True)50 return request('GET', url, **kwargs)51 52 53 def head(url, **kwargs):102-54 """Sends a HEAD request. Returns :class:`Response` object.55 56 :param url: URL for the new :class:`Request` object.106- :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.107- :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.108- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.109- :param auth: (optional) AuthObject to enable Basic HTTP Auth.110- :param timeout: (optional) Float describing the timeout of the request.111- :param allow_redirects: (optional) Boolean. Set to False to disable redirect following.112- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.57+ :param **kwargs: Optional arguments that ``request`` takes.58 """59 60 kwargs.setdefault('allow_redirects', True)61 return request('HEAD', url, **kwargs)62 63 64 def post(url, data='', **kwargs):120-65 """Sends a POST request. Returns :class:`Response` object.66 67 :param url: URL for the new :class:`Request` object.68 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.125- :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.126- :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.127- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.128- :param auth: (optional) AuthObject to enable Basic HTTP Auth.129- :param timeout: (optional) Float describing the timeout of the request.130- :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.131- :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.132- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.69+ :param **kwargs: Optional arguments that ``request`` takes.70 """71 135- return request('POST', url, data=data, **kwargs)72+ return request('post', url, data=data, **kwargs)73 74 75 def put(url, data='', **kwargs):76 """Sends a PUT request. Returns :class:`Response` object.77 78 :param url: URL for the new :class:`Request` object.79 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.143- :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.144- :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.145- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.146- :param auth: (optional) AuthObject to enable Basic HTTP Auth.147- :param timeout: (optional) Float describing the timeout of the request.148- :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.149- :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.150- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.80+ :param **kwargs: Optional arguments that ``request`` takes.81 """82 153- return request('PUT', url, data=data, **kwargs)83+ return request('put', url, data=data, **kwargs)84 85 86 def patch(url, data='', **kwargs):87 """Sends a PATCH request. Returns :class:`Response` object.88 89 :param url: URL for the new :class:`Request` object.90 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.161- :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.162- :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.163- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.164- :param auth: (optional) AuthObject to enable Basic HTTP Auth.165- :param timeout: (optional) Float describing the timeout of the request.166- :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.167- :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.168- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.91+ :param **kwargs: Optional arguments that ``request`` takes.92 """93 171- return request('PATCH', url, **kwargs)94+ return request('patch', url, data=data, **kwargs)95 96 97 def delete(url, **kwargs):175-98 """Sends a DELETE request. Returns :class:`Response` object.99 100 :param url: URL for the new :class:`Request` object.179- :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.180- :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.181- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.182- :param auth: (optional) AuthObject to enable Basic HTTP Auth.183- :param timeout: (optional) Float describing the timeout of the request.184- :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.185- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.101+ :param **kwargs: Optional arguments that ``request`` takes.102 """103 188- return request('DELETE', url, **kwargs)104+ return request('delete', url, **kwargs)modified:requests/async.py+62 added-25 removed
1 # -*- coding: utf-8 -*-2 3 """4- requests.async5- ~~~~~~~~~~~~~~4+requests.async5+~~~~~~~~~~~~~~6 7- This module implements the main Requests system, after monkey-patching8- the urllib2 module with eventlet or gevent..9-10- :copyright: (c) 2011 by Kenneth Reitz.11- :license: ISC, see LICENSE for more details.7+This module contains an asynchronous replica of ``requests.api``, powered8+by gevent. All API methods return a ``Request`` instance (as opposed to9+``Response``). A list of requests can be sent with ``map()``.10 """11 12+try:13+ import gevent14+ from gevent import monkey as curious_george15+except ImportError:16+ raise RuntimeError('Gevent is required for requests.async.')17 15-from __future__ import absolute_import18+# Monkey-patch.19+curious_george.patch_all(thread=False)20 17-import urllib18-import urllib221+from . import api22+from .hooks import dispatch_hook23 20-from urllib2 import HTTPError24 25+__all__ = (26+ 'map',27+ 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'28+)29 23-try:24- import eventlet25- eventlet.monkey_patch()26-except ImportError:27- pass30 29-if not 'eventlet' in locals():30- try:31- from gevent import monkey32- monkey.patch_all()33- except ImportError:34- pass31+def patched(f):32+ """Patches a given API function to not send."""33 34+ def wrapped(*args, **kwargs):35+ return f(*args, return_response=False, **kwargs)36 37-if not 'eventlet' in locals():38- raise ImportError('No Async adaptations of urllib2 found!')37+ return wrapped38 39 41-from .core import *40+def send(r, pools=None):41+ """Sends a given Request object."""42+43+ if pools:44+ r._pools = pools45+46+ r.send()47+48+ return r.response49+50+51+# Patched requests.api functions.52+get = patched(api.get)53+head = patched(api.head)54+post = patched(api.post)55+put = patched(api.put)56+patch = patched(api.patch)57+delete = patched(api.delete)58+request = patched(api.request)59+60+61+def map(requests, prefetch=True):62+ """Concurrently converts a list of Requests to Responses.63+64+ :param requests: a collection of Request objects.65+ :param prefetch: If False, the content will not be downloaded immediately.66+ """67+68+ jobs = [gevent.spawn(send, r) for r in requests]69+ gevent.joinall(jobs)70+71+ if prefetch:72+ [r.response.content for r in requests]73+74+ return [r.response for r in requests]75+76+77+78+added:requests/auth.py+151 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.auth5+~~~~~~~~~~~~~6+7+This module contains the authentication handlers for Requests.8+"""9+10+import time11+import hashlib12+13+from base64 import b64encode14+from urlparse import urlparse15+16+from .utils import randombytes, parse_dict_header17+18+19+def http_basic(r, username, password):20+ """Attaches HTTP Basic Authentication to the given Request object.21+ Arguments should be considered non-positional.22+23+ """24+ username = str(username)25+ password = str(password)26+27+ auth_s = b64encode('%s:%s' % (username, password))28+ r.headers['Authorization'] = ('Basic %s' % auth_s)29+30+ return r31+32+33+def http_digest(r, username, password):34+ """Attaches HTTP Digest Authentication to the given Request object.35+ Arguments should be considered non-positional.36+ """37+38+ def handle_401(r):39+ """Takes the given response and tries digest-auth, if needed."""40+41+ s_auth = r.headers.get('www-authenticate', '')42+43+ if 'digest' in s_auth.lower():44+45+ last_nonce = ''46+ nonce_count = 047+48+ chal = parse_dict_header(s_auth.replace('Digest ', ''))49+50+ realm = chal['realm']51+ nonce = chal['nonce']52+ qop = chal.get('qop')53+ algorithm = chal.get('algorithm', 'MD5')54+ opaque = chal.get('opaque', None)55+56+ algorithm = algorithm.upper()57+ # lambdas assume digest modules are imported at the top level58+ if algorithm == 'MD5':59+ H = lambda x: hashlib.md5(x).hexdigest()60+ elif algorithm == 'SHA':61+ H = lambda x: hashlib.sha1(x).hexdigest()62+ # XXX MD5-sess63+ KD = lambda s, d: H("%s:%s" % (s, d))64+65+ if H is None:66+ return None67+68+ # XXX not implemented yet69+ entdig = None70+ path = urlparse(r.request.url).path71+72+ A1 = "%s:%s:%s" % (username, realm, password)73+ A2 = "%s:%s" % (r.request.method, path)74+75+ if qop == 'auth':76+ if nonce == last_nonce:77+ nonce_count += 178+ else:79+ nonce_count = 180+ last_nonce = nonce81+82+ ncvalue = '%08x' % nonce_count83+ cnonce = (hashlib.sha1("%s:%s:%s:%s" % (84+ nonce_count, nonce, time.ctime(), randombytes(8)))85+ .hexdigest()[:16]86+ )87+ noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))88+ respdig = KD(H(A1), noncebit)89+ elif qop is None:90+ respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))91+ else:92+ # XXX handle auth-int.93+ return None94+95+ # XXX should the partial digests be encoded too?96+ base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \97+ 'response="%s"' % (username, realm, nonce, path, respdig)98+ if opaque:99+ base += ', opaque="%s"' % opaque100+ if entdig:101+ base += ', digest="%s"' % entdig102+ base += ', algorithm="%s"' % algorithm103+ if qop:104+ base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)105+106+107+ r.request.headers['Authorization'] = 'Digest %s' % (base)108+ r.request.send(anyway=True)109+ _r = r.request.response110+ _r.history.append(r)111+ print _r.status_code112+113+ # r.request.response114+115+ print locals()116+117+ print _r.headers118+ return _r119+120+ return r121+122+ r.hooks['response'] = handle_401123+ return r124+125+126+def dispatch(t):127+ """Given an auth tuple, return an expanded version."""128+129+ if not t:130+ return t131+ else:132+ t = list(t)133+134+ # Make sure they're passing in something.135+ assert len(t) >= 2136+137+ # If only two items are passed in, assume HTTPBasic.138+ if (len(t) == 2):139+ t.insert(0, 'basic')140+141+ # Allow built-in string referenced auths.142+ if isinstance(t[0], basestring):143+ if t[0] in ('basic', 'forced_basic'):144+ t[0] = http_basic145+ elif t[0] in ('digest',):146+ t[0] = http_digest147+148+ # Return a custom callable.149+ return (t[0], tuple(t[1:]))150+151+deleted:requests/config.py-67 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.config5-~~~~~~~~~~~~~~~6-7-This module provides the Requests settings feature set.8-9-"""10-11-class Settings(object):12- _singleton = {}13-14- # attributes with defaults15- __attrs__ = []16-17- def __init__(self, **kwargs):18- super(Settings, self).__init__()19-20- self.__dict__ = self._singleton21-22-23- def __call__(self, *args, **kwargs):24- # new instance of class to call25- r = self.__class__()26-27- # cache previous settings for __exit__28- r.__cache = self.__dict__.copy()29- map(self.__cache.setdefault, self.__attrs__)30-31- # set new settings32- self.__dict__.update(*args, **kwargs)33-34- return r35-36-37- def __enter__(self):38- pass39-40-41- def __exit__(self, *args):42-43- # restore cached copy44- self.__dict__.update(self.__cache.copy())45- del self.__cache46-47-48- def __getattribute__(self, key):49- if key in object.__getattribute__(self, '__attrs__'):50- try:51- return object.__getattribute__(self, key)52- except AttributeError:53- return None54- return object.__getattribute__(self, key)55-56-57-settings = Settings()58-59-settings.base_headers = {'User-Agent': 'python-requests.org'}60-settings.accept_gzip = True61-settings.proxies = None62-settings.verbose = None63-settings.timeout = None64-settings.max_redirects = 3065-66-#: Use socket.setdefaulttimeout() as fallback?67-settings.timeout_fallback = Truedeleted:requests/core.py-27 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.core5-~~~~~~~~~~~~~6-7-This module implements the main Requests system.8-9-:copyright: (c) 2011 by Kenneth Reitz.10-:license: ISC, see LICENSE for more details.11-12-"""13-14-__title__ = 'requests'15-__version__ = '0.6.1'16-__build__ = 0x00060117-__author__ = 'Kenneth Reitz'18-__license__ = 'ISC'19-__copyright__ = 'Copyright 2011 Kenneth Reitz'20-21-22-from models import HTTPError23-from api import *24-from exceptions import *25-from sessions import session26-from status_codes import codes27-from config import settingsadded:requests/defaults.py+38 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.defaults5+~~~~~~~~~~~~~~~~~6+7+This module provides the Requests configuration defaults.8+9+settings parameters: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?18+19+"""20+21+from . import __version__22+23+defaults = dict()24+25+26+defaults['base_headers'] = {27+ 'User-Agent': 'python-requests/%s' % __version__,28+ 'Accept-Encoding': ', '.join(('identity', 'deflate', 'compress', 'gzip')),29+}30+31+defaults['proxies'] = {}32+defaults['verbose'] = None33+defaults['timeout'] = None34+defaults['max_redirects'] = 3035+defaults['decode_unicode'] = True36+defaults['timeout_fallback'] = True37+# defaults['keep_alive'] = True38+# defaults['max_connections'] = 10modified:requests/exceptions.py+5 added-6 removed
1 # -*- coding: utf-8 -*-2 3 """4 requests.exceptions5-~~~~~~~~~~~~~~~5+~~~~~~~~~~~~~~~~~~~6 7+This module contains the set of Requests' exceptions.8+9 """10 11 class RequestException(Exception):10- """There was an ambiguous exception that occured while handling your12+ """There was an ambiguous exception that occurred while handling your13 request."""14 15 class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15- 17+18 class Timeout(RequestException):19 """The request timed out."""20 21 class URLRequired(RequestException):22 """A valid URL is required to make a request."""23 22-class InvalidMethod(RequestException):23- """An inappropriate method was attempted."""24-24 class TooManyRedirects(RequestException):25 """Too many redirects."""modified:requests/hooks.py+1 added-1 removed
24 unmodified lines25 import warnings26 27 28 def dispatch_hook(key, hooks, hook_data):29- """Dipatches a hook dictionary on a given peice of data."""29+ """Dispatches a hook dictionary on a given piece of data."""30 31 hooks = hooks or dict()32 33 if key in hooks:7 unmodified linesmodified:requests/models.py+178 added-280 removed
1+2 # -*- coding: utf-8 -*-3 4 """5 requests.models9 unmodified lines15 from urllib2 import HTTPError16 from urlparse import urlparse, urlunparse, urljoin17 from datetime import datetime18 18-from .config import settings19-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19+from .hooks import dispatch_hook20 from .structures import CaseInsensitiveDict21 from .packages.poster.encode import multipart_encode22 from .packages.poster.streaminghttp import register_openers, get_handlers23-from .utils import dict_from_cookiejar24-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects23+from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)24 from .status_codes import codes25+from .exceptions import Timeout, URLRequired, TooManyRedirects26+from .monkeys import Request as _Request27+from .monkeys import HTTPRedirectHandler28 29+from .auth import dispatch as auth_dispatch30 31 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)32 33 34 35 class Request(object):33- """The :class:`Request <models.Request>` object. It carries out all functionality of36+ """The :class:`Request <Request>` object. It carries out all functionality of37 Requests. Recommended interface is with the Requests functions.38 """39 40 def __init__(self,38- url=None, headers=dict(), files=None, method=None, data=dict(),39- params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,40- allow_redirects=False, proxies=None):41+ url=None,42+ headers=dict(),43+ files=None,44+ method=None,45+ data=dict(),46+ params=dict(),47+ auth=None,48+ cookies=None,49+ timeout=None,50+ redirect=False,51+ allow_redirects=False,52+ proxies=None,53+ hooks=None,54+ config=None):55 42- #: Float describ the timeout of the request.56+ #: Float describes the timeout of the request.57 # (Use socket.setdefaulttimeout() as fallback)58 self.timeout = timeout59 60 #: Request URL.61 self.url = url62 49- #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.63+ #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.64 self.headers = headers65 66 #: Dictionary of files to multipart upload (``{filename: content}``).67 self.files = files68 55- #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.69+ #: HTTP Method to use.70 self.method = method71 72 #: Dictionary or byte of request body data to attach to the59- #: :class:`Request <models.Request>`.73+ #: :class:`Request <Request>`.74 self.data = None75 76 #: Dictionary or byte of querystring data to attach to the63- #: :class:`Request <models.Request>`.77+ #: :class:`Request <Request>`.78 self.params = None79 66- #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history80+ #: True if :class:`Request <Request>` is part of a redirect chain (disables history81 #: and HTTPError storage).82 self.redirect = redirect83 84 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)4 unmodified lines89 90 self.data, self._enc_data = self._encode_params(data)91 self.params, self._enc_params = self._encode_params(params)92 79- #: :class:`Response <models.Response>` instance, containing93+ #: :class:`Response <Response>` instance, containing94 #: content and metadata of HTTP Response, once :attr:`sent <send>`.95 self.response = Response()96 83- if isinstance(auth, (list, tuple)):84- auth = AuthObject(*auth)85- if not auth:86- auth = auth_manager.get_auth(self.url)97+ #: Authentication tuple to attach to :class:`Request <Request>`.98+ self.auth = auth_dispatch(auth)99 88- #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89- self.auth = auth100+ #: CookieJar to attach to :class:`Request <Request>`.101+ self.cookies = cookies102 91- #: CookieJar to attach to :class:`Request <models.Request>`.92- self.cookiejar = cookiejar103+ #: Dictionary of configurations for this request.104+ self.config = config105 106 #: True if Request has been sent.107 self.sent = False108 109+ #: Event-handling hooks.110+ self.hooks = hooks111 98- # Header manipulation and defaults.99-100- if settings.accept_gzip:101- settings.base_headers.update({'Accept-Encoding': 'gzip'})102-112 if headers:113 headers = CaseInsensitiveDict(self.headers)114 else:115 headers = CaseInsensitiveDict()116 108- for (k, v) in settings.base_headers.items():117+ for (k, v) in self.config.get('base_headers', {}).items():118 if k not in headers:119 headers[k] = v120 121 self.headers = headers122 123+ # Pre-request hook.124+ r = dispatch_hook('pre_request', hooks, self)125+ self.__dict__.update(r.__dict__)126 127+128 def __repr__(self):129 return '<Request [%s]>' % (self.method)130 131 119- def _checks(self):120- """Deterministic checks for consistency."""121-122- if not self.url:123- raise URLRequired124-125-132 def _get_opener(self):133 """Creates appropriate opener object for urllib2."""134 135 _handlers = []136 131- if self.cookiejar is not None:132- _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))137+ if self.cookies is not None:138+ _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))139 134- if self.auth:135- if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):136- # TODO: REMOVE THIS COMPLETELY137- auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)138- self.auth.handler = self.auth.handler(auth_manager)139- auth_manager.add_auth(self.url, self.auth)140-141- _handlers.append(self.auth.handler)142-140 if self.proxies:141 _handlers.append(urllib2.ProxyHandler(self.proxies))142 143 _handlers.append(HTTPRedirectHandler)18 unmodified lines162 return opener.open163 164 165 def _build_response(self, resp, is_error=False):169- """Build internal :class:`Response <models.Response>` object from given response."""166+ """Build internal :class:`Response <Response>` object167+ from given response.168+ """169 170+171 def build(resp):172 173 response = Response()174+ response.config = self.config175 response.status_code = getattr(resp, 'code', None)176 177 try:178 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))178- response.read = resp.read179- response._resp = resp180- response._close = resp.close179+ response.raw = resp180 182- if self.cookiejar:181+ if self.cookies:182+ response.cookies = dict_from_cookiejar(self.cookies)183 184- response.cookies = dict_from_cookiejar(self.cookiejar)184 186-185 except AttributeError:186 pass187 188 if is_error:14 unmodified lines203 ('location' in r.headers) and204 ((r.status_code is codes.see_other) or (self.allow_redirects))205 ):206 209- r.close()207+ r.raw.close()208 211- if not len(history) < settings.max_redirects:209+ if not len(history) < self.config.get('max_redirects'):210 raise TooManyRedirects()211 212 history.append(r)213 15 unmodified lines229 else:230 method = self.method231 232 request = Request(235- url, self.headers, self.files, method,236- self.data, self.params, self.auth, self.cookiejar,237- redirect=True233+ url=url,234+ headers=self.headers,235+ files=self.files,236+ method=method,237+ # data=self.data,238+ # params=self.params,239+ auth=self.auth,240+ cookies=self.cookies,241+ redirect=True,242+ config=self.config243 )244 request.send()245 r = request.response246 12 unmodified lines259 version of that.260 261 Otherwise, assumes the data is already encoded appropriately, and262 returns it twice.258-263 """264+265 if hasattr(data, 'items'):266 result = []267 for k, vs in data.items():268 for v in isinstance(vs, list) and vs or [vs]:34 unmodified lines303 :param anyway: If True, request will be sent, even if it has304 already been sent.305 """306 302- self._checks()303- success = False307+ # Some people...308+ if not self.url:309+ raise URLRequired310 311 # Logging306- if settings.verbose:307- settings.verbose.write('%s %s %s\n' % (312+ if self.config.get('verbose'):313+ self.config.get('verbose').write('%s %s %s\n' % (314 datetime.now().isoformat(), self.method, self.url315 ))316 311-317+ # Build the URL318 url = self._build_url()313- if self.method in ('GET', 'HEAD', 'DELETE'):314- req = _Request(url, method=self.method)319+320+ # Attach uploaded files.321+ if self.files:322+ register_openers()323+324+ # Add form-data to the multipart.325+ if self.data:326+ self.files.update(self.data)327+328+ data, headers = multipart_encode(self.files)329+330 else:331+ data = self._enc_data332+ headers = {}333 317- if self.files:318- register_openers()334+ if self.auth:335+ auth_func, auth_args = self.auth336 320- if self.data:321- self.files.update(self.data)337+ r = auth_func(self, *auth_args)338 323- datagen, headers = multipart_encode(self.files)324- req = _Request(url, data=datagen, headers=headers, method=self.method)339+ self.__dict__.update(r.__dict__)340 326- else:327- req = _Request(url, data=self._enc_data, method=self.method)341+ # Build the Urllib2 Request.342+ req = _Request(url, data=data, headers=headers, method=self.method)343 344+ # Add the headers to the request.345 if self.headers:346 for k,v in self.headers.iteritems():347 req.add_header(k, v)348 9 unmodified lines358 # timeout argument is new since Python v2.6359 if not 'timeout' in str(err):360 raise361 346- if settings.timeout_fallback:362+ if self.config.get('timeout_fallback'):363 # fall-back and use global socket timeout (This is not thread-safe!)364 old_timeout = socket.getdefaulttimeout()365 socket.setdefaulttimeout(self.timeout)366 367 resp = opener(req)368 353- if settings.timeout_fallback:354- # restore gobal timeout369+ if self.config.get('timeout_fallback'):370+ # restore global timeout371 socket.setdefaulttimeout(old_timeout)372 357- if self.cookiejar is not None:358- self.cookiejar.extract_cookies(resp, req)373+ if self.cookies is not None:374+ self.cookies.extract_cookies(resp, req)375 376 except (urllib2.HTTPError, urllib2.URLError), why:377 if hasattr(why, 'reason'):378 if isinstance(why.reason, socket.timeout):379 why = Timeout(why)380+ elif isinstance(why.reason, socket.error):381+ why = Timeout(why)382 383 self._build_response(why, is_error=True)384 367-385 else:386 self._build_response(resp)387 self.response.ok = True388 389 390 self.sent = self.response.ok391 375- return self.sent392+ # Response manipulation hook.393+ self.response = dispatch_hook('response', self.hooks, self.response)394 395+ # Post-request hook.396+ r = dispatch_hook('post_request', self.hooks, self)397+ self.__dict__.update(r.__dict__)398 399+ return self.sent400 401+402 class Response(object):380- """The core :class:`Response <models.Response>` object. All381- :class:`Request <models.Request>` objects contain a382- :class:`response <models.Response>` attribute, which is an instance403+ """The core :class:`Response <Response>` object. All404+ :class:`Request <Request>` objects contain a405+ :class:`response <Response>` attribute, which is an instance406 of this class.407 """408 409 def __init__(self):387- #: Raw content of the response, in bytes.388- #: If ``content-encoding`` of response was set to ``gzip``, the389- #: response data will be automatically deflated.410+411 self._content = None412+ self._content_consumed = False413+414 #: Integer Code of responded HTTP Status.415 self.status_code = None416+417 #: Case-insensitive Dictionary of Response Headers.418 #: For example, ``headers['content-encoding']`` will return the419 #: value of a ``'Content-Encoding'`` response header.420 self.headers = CaseInsensitiveDict()421+422+ #: File-like object representation of response (for advanced usage).423+ self.raw = None424+425 #: Final URL location of Response.426 self.url = None427+399- #: True if no :attr:`error` occured.428+ #: True if no :attr:`error` occurred.429 self.ok = False430+401- #: Resulting :class:`HTTPError` of request, if one occured.431+ #: Resulting :class:`HTTPError` of request, if one occurred.432 self.error = None433+403- #: A list of :class:`Response <models.Response>` objects from434+ #: A list of :class:`Response <Response>` objects from435 #: the history of the Request. Any redirect responses will end436 #: up here.437 self.history = []438+407- #: The Request that created the Response.439+ #: The :class:`Request <Request>` that created the Response.440 self.request = None441+442 #: A dictionary of Cookies the server sent back.443 self.cookies = None444 445+ #: Dictionary of configurations for this request.446+ self.config = None447 448+449 def __repr__(self):450 return '<Response [%s]>' % (self.status_code)451 452 453 def __nonzero__(self):454 """Returns true if :attr:`status_code` is 'OK'."""455+456 return not self.error457 458+ def iter_content(self, chunk_size=10 * 1024, decode_unicode=None):459+ """Iterates over the response data. This avoids reading the content460+ at once into memory for large responses. The chunk size is the number461+ of bytes it should read into memory. This is not necessarily the462+ length of each item returned as decoding can take place.463+ """464+ if self._content_consumed:465+ raise RuntimeError('The content for this response was '466+ 'already consumed')467 422- def __getattr__(self, name):423- """Read and returns the full stream when accessing to :attr: `content`"""424- if name == 'content':425- if self._content is not None:426- return self._content427- self._content = self.read()428- if self.headers.get('content-encoding', '') == 'gzip':429- try:430- self._content = zlib.decompress(self._content, 16+zlib.MAX_WBITS)431- except zlib.error:432- pass433- return self._content434- else:435- raise AttributeError468+ def generate():469+ while 1:470+ chunk = self.raw.read(chunk_size)471+ if not chunk:472+ break473+ yield chunk474+ self._content_consumed = True475+ gen = generate()476+ if 'gzip' in self.headers.get('content-encoding', ''):477+ gen = stream_decode_gzip(gen)478+ if decode_unicode is None:479+ decode_unicode = self.config.get('decode_unicode')480+ if decode_unicode:481+ gen = stream_decode_response_unicode(gen, self)482+ return gen483 437- def raise_for_status(self):438- """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""439- if self.error:440- raise self.error484+ @property485+ def content(self):486+ """Content of the response, in bytes or unicode487+ (if available).488+ """489 490+ if self._content is not None:491+ return self._content492 443- def close(self):444- if self._resp.fp is not None and hasattr(self._resp.fp, '_sock'):445- self._resp.fp._sock.recv = None446- self._close()493+ if self._content_consumed:494+ raise RuntimeError('The content for this response was '495+ 'already consumed')496 448-class AuthManager(object):449- """Requests Authentication Manager."""497+ # Read the contents.498+ self._content = self.raw.read()499 451- def __new__(cls):452- singleton = cls.__dict__.get('__singleton__')453- if singleton is not None:454- return singleton455-456- cls.__singleton__ = singleton = object.__new__(cls)457-458- return singleton459-460-461- def __init__(self):462- self.passwd = {}463- self._auth = {}464-465-466- def __repr__(self):467- return '<AuthManager [%s]>' % (self.method)468-469-470- def add_auth(self, uri, auth):471- """Registers AuthObject to AuthManager."""472-473- uri = self.reduce_uri(uri, False)474-475- # try to make it an AuthObject476- if not isinstance(auth, AuthObject):500+ # Decode GZip'd content.501+ if 'gzip' in self.headers.get('content-encoding', ''):502 try:478- auth = AuthObject(*auth)479- except TypeError:503+ self._content = decode_gzip(self._content)504+ except zlib.error:505 pass506 482- self._auth[uri] = auth507+ # Decode unicode content.508+ if self.config.get('decode_unicode'):509+ self._content = get_unicode_from_response(self)510 511+ self._content_consumed = True512+ return self._content513 485- def add_password(self, realm, uri, user, passwd):486- """Adds password to AuthManager."""487- # uri could be a single URI or a sequence488- if isinstance(uri, basestring):489- uri = [uri]514 491- reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])515+ def raise_for_status(self):516+ """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""517+ if self.error:518+ raise self.error519 493- if reduced_uri not in self.passwd:494- self.passwd[reduced_uri] = {}495- self.passwd[reduced_uri] = (user, passwd)496-497-498- def find_user_password(self, realm, authuri):499- for uris, authinfo in self.passwd.iteritems():500- reduced_authuri = self.reduce_uri(authuri, False)501- for uri in uris:502- if self.is_suburi(uri, reduced_authuri):503- return authinfo504-505- return (None, None)506-507-508- def get_auth(self, uri):509- (in_domain, in_path) = self.reduce_uri(uri, False)510-511- for domain, path, authority in (512- (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()513- ):514- if in_domain == domain:515- if path in in_path:516- return authority517-518-519- def reduce_uri(self, uri, default_port=True):520- """Accept authority or URI and extract only the authority and path."""521-522- # note HTTP URLs do not have a userinfo component523- parts = urllib2.urlparse.urlsplit(uri)524-525- if parts[1]:526- # URI527- scheme = parts[0]528- authority = parts[1]529- path = parts[2] or '/'530- else:531- # host or host:port532- scheme = None533- authority = uri534- path = '/'535-536- host, port = urllib2.splitport(authority)537-538- if default_port and port is None and scheme is not None:539- dport = {"http": 80,540- "https": 443,541- }.get(scheme)542- if dport is not None:543- authority = "%s:%d" % (host, dport)544-545- return authority, path546-547-548- def is_suburi(self, base, test):549- """Check if test is below base in a URI tree550-551- Both args must be URIs in reduced form.552- """553- if base == test:554- return True555- if base[0] != test[0]:556- return False557- common = urllib2.posixpath.commonprefix((base[1], test[1]))558- if len(common) == len(base[1]):559- return True560- return False561-562-563- def empty(self):564- self.passwd = {}565-566-567- def remove(self, uri, realm=None):568- # uri could be a single URI or a sequence569- if isinstance(uri, basestring):570- uri = [uri]571-572- for default_port in True, False:573- reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])574- del self.passwd[reduced_uri][realm]575-576-577- def __contains__(self, uri):578- # uri could be a single URI or a sequence579- if isinstance(uri, basestring):580- uri = [uri]581-582- uri = tuple([self.reduce_uri(u, False) for u in uri])583-584- if uri in self.passwd:585- return True586-587- return False588-589-auth_manager = AuthManager()590-591-592-593-class AuthObject(object):594- """The :class:`AuthObject` is a simple HTTP Authentication token. When595- given to a Requests function, it enables Basic HTTP Authentication for that596- Request. You can also enable Authorization for domain realms with AutoAuth.597- See AutoAuth for more details.598-599- :param username: Username to authenticate with.600- :param password: Password for given username.601- :param realm: (optional) the realm this auth applies to602- :param handler: (optional) basic || digest || proxy_basic || proxy_digest603- """604-605- _handlers = {606- 'basic': HTTPBasicAuthHandler,607- 'forced_basic': HTTPForcedBasicAuthHandler,608- 'digest': HTTPDigestAuthHandler,609- 'proxy_basic': urllib2.ProxyBasicAuthHandler,610- 'proxy_digest': urllib2.ProxyDigestAuthHandler611- }612-613- def __init__(self, username, password, handler='forced_basic', realm=None):614- self.username = username615- self.password = password616- self.realm = realm617-618- if isinstance(handler, basestring):619- self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)620- else:621- self.handler = handlermodified:requests/monkeys.py+5 added-114 removed
27 unmodified lines28 29 30 class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31 """HTTP Redirect handler."""32- def http_error_301(self, req, fp, code, msg, headers):32+ def _pass(self, req, fp, code, msg, headers):33 pass34 35- http_error_302 = http_error_303 = http_error_307 = http_error_30135+ http_error_302 = _pass36+ http_error_303 = _pass37+ http_error_307 = _pass38+ http_error_301 = _pass39 37-38-39-class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):40- """HTTP Basic Auth Handler with authentication loop fixes."""41-42- def __init__(self, *args, **kwargs):43- urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44- self.retried_req = None45- self.retried = 046-47-48- def reset_retry_count(self):49- # Python 2.6.5 will call this on 401 or 407 errors and thus loop50- # forever. We disable reset_retry_count completely and reset in51- # http_error_auth_reqed instead.52- pass53-54-55- def http_error_auth_reqed(self, auth_header, host, req, headers):56- # Reset the retry counter once for each request.57- if req is not self.retried_req:58- self.retried_req = req59- self.retried = 060-61- return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(62- self, auth_header, host, req, headers63- )64-65-66-67-class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):68- """HTTP Basic Auth Handler with forced Authentication."""69-70- auth_header = 'Authorization'71- rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'72- 'realm=(["\'])(.*?)\\2', re.I)73-74- def __init__(self, *args, **kwargs):75- HTTPBasicAuthHandler.__init__(self, *args, **kwargs)76-77-78- def http_error_401(self, req, fp, code, msg, headers):79- url = req.get_full_url()80- response = self._http_error_auth_reqed('www-authenticate', url, req, headers)81- self.reset_retry_count()82- return response83-84- http_error_404 = http_error_40185-86-87- def _http_error_auth_reqed(self, authreq, host, req, headers):88-89- authreq = headers.get(authreq, None)90-91- if self.retried > 5:92- # retry sending the username:password 5 times before failing.93- raise urllib2.HTTPError(req.get_full_url(), 401, "basic auth failed",94- headers, None)95- else:96- self.retried += 197-98- if authreq:99-100- mo = self.rx.search(authreq)101-102- if mo:103- scheme, quote, realm = mo.groups()104-105- if scheme.lower() == 'basic':106- response = self.retry_http_basic_auth(host, req, realm)107-108- if response and response.code not in (401, 404):109- self.retried = 0110- return response111- else:112- response = self.retry_http_basic_auth(host, req, 'Realm')113-114- if response and response.code not in (401, 404):115- self.retried = 0116- return response117-118-119-120-class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):121-122- def __init__(self, *args, **kwargs):123- urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)124- self.retried_req = None125-126- def reset_retry_count(self):127- # Python 2.6.5 will call this on 401 or 407 errors and thus loop128- # forever. We disable reset_retry_count completely and reset in129- # http_error_auth_reqed instead.130- pass131-132- def http_error_auth_reqed(self, auth_header, host, req, headers):133- # Reset the retry counter once for each request.134- if req is not self.retried_req:135- self.retried_req = req136- self.retried = 0137- # In python < 2.5 AbstractDigestAuthHandler raises a ValueError if138- # it doesn't know about the auth type requested. This can happen if139- # somebody is using BasicAuth and types a bad password.140-141- try:142- return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(143- self, auth_header, host, req, headers)144- except ValueError, inst:145- arg = inst.args[0]146- if arg.startswith("AbstractDigestAuthHandler doesn't know "):147- return148- raisedeleted:requests/patches.py-5 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.monkeys5-"""modified:requests/sessions.py+200 added-39 removed
1 # -*- coding: utf-8 -*-2 3 """4 requests.session5-~~~~~~~~~~~~~~~5+~~~~~~~~~~~~~~~~6 7 This module provides a Session object to manage and persist settings across8 requests (cookies, auth, proxies).9 10 """11 12 import cookielib13 14-from . import api15-from .utils import add_dict_to_cookiejar14+from .defaults import defaults15+from .models import Request16+from .hooks import dispatch_hook17+from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18 19 20+def merge_kwargs(local_kwarg, default_kwarg):21+ """Merges kwarg dictionaries.22 23+ If a local key in the dictionary is set to None, it will be removed.24+ """25+26+ if default_kwarg is None:27+ return local_kwarg28+29+ if isinstance(local_kwarg, basestring):30+ return local_kwarg31+32+ if local_kwarg is None:33+ return default_kwarg34+35+ # Bypass if not a dictionary (e.g. timeout)36+ if not hasattr(default_kwarg, 'items'):37+ return local_kwarg38+39+ # Update new values.40+ kwargs = default_kwarg.copy()41+ kwargs.update(local_kwarg)42+43+ # Remove keys that are set to None.44+ for (k,v) in local_kwarg.items():45+ if v is None:46+ del kwargs[k]47+48+ return kwargs49+50+51 class Session(object):52 """A Requests session."""53 22- __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']54+ __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params', 'config']55 56 25- def __init__(self, **kwargs):57+ def __init__(self,58+ headers=None,59+ cookies=None,60+ auth=None,61+ timeout=None,62+ proxies=None,63+ hooks=None,64+ params=None,65+ config=None):66 67+ self.headers = headers or {}68+ self.cookies = cookies or {}69+ self.auth = auth70+ self.timeout = timeout71+ self.proxies = proxies or {}72+ self.hooks = hooks or {}73+ self.params = params or {}74+ self.config = config or {}75+76+ for (k, v) in defaults.items():77+ self.config.setdefault(k, v)78+79 # Set up a CookieJar to be used by default80 self.cookies = cookielib.FileCookieJar()81 30- # Map args from kwargs to instance-local variables31- map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),32- kwargs.iterkeys(), kwargs.itervalues())33-34- # Map and wrap requests.api methods35- self._map_api_methods()36-37-82 def __repr__(self):83 return '<requests-client at 0x%x>' % (id(self))84 85 def __enter__(self):86 return self87 88 def __exit__(self, *args):45- # print args89 pass90 91+ def request(self, method, url,92+ params=None,93+ data=None,94+ headers=None,95+ cookies=None,96+ files=None,97+ auth=None,98+ timeout=None,99+ allow_redirects=False,100+ proxies=None,101+ hooks=None,102+ return_response=True,103+ config=None):104 49- def _map_api_methods(self):50- """Reads each available method from requests.api and decorates51- them with a wrapper, which inserts any instance-local attributes52- (from __attrs__) that have been set, combining them with **kwargs.105+ """Constructs and sends a :class:`Request <Request>`.106+ Returns :class:`Response <Response>` object.107+108+ :param method: method for the new :class:`Request` object.109+ :param url: URL for the new :class:`Request` object.110+ :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.111+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.112+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.113+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.114+ :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.115+ :param auth: (optional) Auth typle to enable Basic/Digest/Custom HTTP Auth.116+ :param timeout: (optional) Float describing the timeout of the request.117+ :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.118+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.119+ :param return_response: (optional) If False, an un-sent Request object will returned.120+ :param config: (optional) A configuration dictionary.121 """122 55- def pass_args(func):56- def wrapper_func(*args, **kwargs):57- inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems()58- if k in self.__attrs__)59- # Combine instance-local values with kwargs values, with60- # priority to values in kwargs61- kwargs = dict(inst_attrs.items() + kwargs.items())123+ method = str(method).upper()124 63- # If a session request has a cookie_dict, inject the64- # values into the existing CookieJar instead.65- if isinstance(kwargs.get('cookies', None), dict):66- kwargs['cookies'] = add_dict_to_cookiejar(67- inst_attrs['cookies'], kwargs['cookies']68- )125+ if cookies is None:126+ cookies = {}127 70- if kwargs.get('headers', None) and inst_attrs.get('headers', None):71- kwargs['headers'].update(inst_attrs['headers'])128+ if isinstance(cookies, dict):129+ cookies = add_dict_to_cookiejar(self.cookies, cookies)130 73- return func(*args, **kwargs)74- return wrapper_func131+ cookies = cookiejar_from_dict(cookies)132 76- # Map and decorate each function available in requests.api77- map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),78- api.__all__)133+ # Expand header values134+ if headers:135+ for k, v in headers.items() or {}:136+ headers[k] = header_expand(v)137 138+ args = dict(139+ method=method,140+ url=url,141+ data=data,142+ params=params,143+ headers=headers,144+ cookies=cookies,145+ files=files,146+ auth=auth,147+ hooks=hooks,148+ timeout=timeout,149+ allow_redirects=allow_redirects,150+ proxies=proxies,151+ config=config152+ )153 154+ for attr in self.__attrs__:155+ session_val = getattr(self, attr, None)156+ local_val = args.get(attr)157+158+ args[attr] = merge_kwargs(local_val, session_val)159+160+ # Arguments manipulation hook.161+ args = dispatch_hook('args', hooks, args)162+163+ r = Request(**args)164+165+ # Don't send if asked nicely.166+ if not return_response:167+ return r168+169+ # Send the HTTP Request.170+ r.send()171+172+173+ return r.response174+175+176+ def get(self, url, **kwargs):177+ """Sends a GET request. Returns :class:`Response` object.178+179+ :param url: URL for the new :class:`Request` object.180+ :param **kwargs: Optional arguments that ``request`` takes.181+ """182+183+ kwargs.setdefault('allow_redirects', True)184+ return self.request('GET', url, **kwargs)185+186+187+ def head(self, url, **kwargs):188+ """Sends a HEAD request. Returns :class:`Response` object.189+190+ :param url: URL for the new :class:`Request` object.191+ :param **kwargs: Optional arguments that ``request`` takes.192+ """193+194+ kwargs.setdefault('allow_redirects', True)195+ return self.request('HEAD', url, **kwargs)196+197+198+ def post(self, url, data='', **kwargs):199+ """Sends a POST request. Returns :class:`Response` object.200+201+ :param url: URL for the new :class:`Request` object.202+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.203+ :param **kwargs: Optional arguments that ``request`` takes.204+ """205+206+ return self.request('post', url, data=data, **kwargs)207+208+209+ def put(self, url, data='', **kwargs):210+ """Sends a PUT request. Returns :class:`Response` object.211+212+ :param url: URL for the new :class:`Request` object.213+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.214+ :param **kwargs: Optional arguments that ``request`` takes.215+ """216+217+ return self.request('put', url, data=data, **kwargs)218+219+220+ def patch(self, url, data='', **kwargs):221+ """Sends a PATCH request. Returns :class:`Response` object.222+223+ :param url: URL for the new :class:`Request` object.224+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.225+ :param **kwargs: Optional arguments that ``request`` takes.226+ """227+228+ return self.request('patch', url, data='', **kwargs)229+230+231+ def delete(self, url, **kwargs):232+ """Sends a DELETE request. Returns :class:`Response` object.233+234+ :param url: URL for the new :class:`Request` object.235+ :param **kwargs: Optional arguments that ``request`` takes.236+ """237+238+ return self.request('delete', url, **kwargs)239+240+241+242 def session(**kwargs):82- """Returns a :class:`Session` for context-managment."""243+ """Returns a :class:`Session` for context-management."""244 245 return Session(**kwargs)modified:requests/status_codes.py+5 added-2 removed
45 unmodified lines46 411: ('length_required',),47 412: ('precondition_failed', 'precondition'),48 413: ('request_entity_too_large',),49 414: ('request_uri_too_large',),50- 415: ('unspported_media_type', 'unspported_media', 'media_type'),50+ 415: ('unsupported_media_type', 'unsupported_media', 'media_type'),51 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),52 417: ('expectation_failed',),53 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),54 422: ('unprocessable_entity', 'unprocessable'),55 423: ('locked',),56- 424: ('failed_depdendency', 'depdendency'),56+ 424: ('failed_dependency', 'dependency'),57 425: ('unordered_collection', 'unordered'),58 426: ('upgrade_required', 'upgrade'),59+ 428: ('precondition_required', 'precondition'),60+ 429: ('too_many_requests', 'too_many'),61+ 431: ('header_fields_too_large', 'fields_too_large'),62 444: ('no_response', 'none'),63 449: ('retry_with', 'retry'),64 450: ('blocked_by_windows_parental_controls', 'parental_controls'),65 499: ('client_closed_request',),21 unmodified linesmodified:requests/structures.py+1 added-1 removed
2 unmodified lines3 """4 requests.structures5 ~~~~~~~~~~~~~~~~~~~6 7-Datastructures that power Requests.7+Data structures that power Requests.8 9 """10 11 class CaseInsensitiveDict(dict):54 unmodified linesmodified:requests/utils.py+296 added-5 removed
7 unmodified lines8 that are also useful for external consumption.9 10 """11 12+import cgi13+import codecs14 import cookielib15+import os16+import random17+import re18+import zlib19 20+from urllib2 import parse_http_list as _parse_list_header21 15-def dict_from_cookiejar(cookiejar):16- """Returns a key/value dictionary from a CookieJar."""22 23+# From mitsuhiko/werkzeug (used with permission).24+def parse_list_header(value):25+ """Parse lists as described by RFC 2068 Section 2.26+27+ In particular, parse comma-separated lists where the elements of28+ the list may include quoted-strings. A quoted-string could29+ contain a comma. A non-quoted string could have quotes in the30+ middle. Quotes are removed automatically after parsing.31+32+ It basically works like :func:`parse_set_header` just that items33+ may appear multiple times and case sensitivity is preserved.34+35+ The return value is a standard :class:`list`:36+37+ >>> parse_list_header('token, "quoted value"')38+ ['token', 'quoted value']39+40+ To create a header from the :class:`list` again, use the41+ :func:`dump_header` function.42+43+ :param value: a string with a list header.44+ :return: :class:`list`45+ """46+ result = []47+ for item in _parse_list_header(value):48+ if item[:1] == item[-1:] == '"':49+ item = unquote_header_value(item[1:-1])50+ result.append(item)51+ return result52+53+54+# From mitsuhiko/werkzeug (used with permission).55+def parse_dict_header(value):56+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and57+ convert them into a python dict:58+59+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')60+ >>> type(d) is dict61+ True62+ >>> sorted(d.items())63+ [('bar', 'as well'), ('foo', 'is a fish')]64+65+ If there is no value for a key it will be `None`:66+67+ >>> parse_dict_header('key_without_value')68+ {'key_without_value': None}69+70+ To create a header from the :class:`dict` again, use the71+ :func:`dump_header` function.72+73+ :param value: a string with a dict header.74+ :return: :class:`dict`75+ """76+ result = {}77+ for item in _parse_list_header(value):78+ if '=' not in item:79+ result[item] = None80+ continue81+ name, value = item.split('=', 1)82+ if value[:1] == value[-1:] == '"':83+ value = unquote_header_value(value[1:-1])84+ result[name] = value85+ return result86+87+88+# From mitsuhiko/werkzeug (used with permission).89+def unquote_header_value(value, is_filename=False):90+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).91+ This does not use the real unquoting but what browsers are actually92+ using for quoting.93+94+ :param value: the header value to unquote.95+ """96+ if value and value[0] == value[-1] == '"':97+ # this is not the real unquoting, but fixing this so that the98+ # RFC is met will result in bugs with internet explorer and99+ # probably some other browsers as well. IE for example is100+ # uploading files with "C:\foo\bar.txt" as filename101+ value = value[1:-1]102+103+ # if this is a filename and the starting characters look like104+ # a UNC path, then just return the value without quotes. Using the105+ # replace sequence below on a UNC path has the effect of turning106+ # the leading double slash into a single slash and then107+ # _fix_ie_filename() doesn't work correctly. See #458.108+ if not is_filename or value[:2] != '\\\\':109+ return value.replace('\\\\', '\\').replace('\\"', '"')110+ return value111+112+113+def header_expand(headers):114+ """Returns an HTTP Header value string from a dictionary.115+116+ Example expansion::117+118+ {'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}}119+ # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c120+121+ (('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {}))122+ # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c123+ """124+125+ collector = []126+127+ if isinstance(headers, dict):128+ headers = headers.items()129+130+ elif isinstance(headers, basestring):131+ return headers132+133+ for i, (value, params) in enumerate(headers):134+135+ _params = []136+137+ for (p_k, p_v) in params.items():138+139+ _params.append('%s=%s' % (p_k, p_v))140+141+ collector.append(value)142+ collector.append('; ')143+144+ if len(params):145+146+ collector.append('; '.join(_params))147+148+ if not len(headers) == i+1:149+ collector.append(', ')150+151+152+ # Remove trailing separators.153+ if collector[-1] in (', ', '; '):154+ del collector[-1]155+156+ return ''.join(collector)157+158+159+160+def randombytes(n):161+ """Return n random bytes."""162+ # Use /dev/urandom if it is available. Fall back to random module163+ # if not. It might be worthwhile to extend this function to use164+ # other platform-specific mechanisms for getting random bytes.165+ if os.path.exists("/dev/urandom"):166+ f = open("/dev/urandom")167+ s = f.read(n)168+ f.close()169+ return s170+ else:171+ L = [chr(random.randrange(0, 256)) for i in range(n)]172+ return "".join(L)173+174+175+def dict_from_cookiejar(cj):176+ """Returns a key/value dictionary from a CookieJar.177+178+ :param cj: CookieJar object to extract cookies from.179+ """180+181 cookie_dict = {}182 20- for _, cookies in cookiejar._cookies.items():183+ for _, cookies in cj._cookies.items():184 for _, cookies in cookies.items():185 for cookie in cookies.values():186 # print cookie187 cookie_dict[cookie.name] = cookie.value1 unmodified line189 return cookie_dict190 191 192 def cookiejar_from_dict(cookie_dict):30- """Returns a CookieJar from a key/value dictionary."""193+ """Returns a CookieJar from a key/value dictionary.194 195+ :param cookie_dict: Dict of key/values to insert into CookieJar.196+ """197+198 # return cookiejar if one was passed in199 if isinstance(cookie_dict, cookielib.CookieJar):200 return cookie_dict201 5 unmodified lines207 return cj208 209 210 def add_dict_to_cookiejar(cj, cookie_dict):45- """Returns a CookieJar from a key/value dictionary."""211+ """Returns a CookieJar from a key/value dictionary.212 213+ :param cj: CookieJar to insert cookies into.214+ :param cookie_dict: Dict of key/values to insert into CookieJar.215+ """216+217 for k, v in cookie_dict.items():218 219 cookie = cookielib.Cookie(220 version=0,18 unmodified lines239 # add cookie to cookiejar240 cj.set_cookie(cookie)241 242 return cj243+244+245+def get_encodings_from_content(content):246+ """Returns encodings from given content string.247+248+ :param content: bytestring to extract encodings from.249+ """250+251+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)252+253+ return charset_re.findall(content)254+255+256+def get_encoding_from_headers(headers):257+ """Returns encodings from given HTTP Header Dict.258+259+ :param headers: dictionary to extract encoding from.260+ """261+262+ content_type = headers.get('content-type')263+264+ if not content_type:265+ return None266+267+ content_type, params = cgi.parse_header(content_type)268+269+ if 'charset' in params:270+ return params['charset'].strip("'\"")271+272+273+def unicode_from_html(content):274+ """Attempts to decode an HTML string into unicode.275+ If unsuccessful, the original content is returned.276+ """277+278+ encodings = get_encodings_from_content(content)279+280+ for encoding in encodings:281+282+ try:283+ return unicode(content, encoding)284+ except (UnicodeError, TypeError):285+ pass286+287+ return content288+289+290+def stream_decode_response_unicode(iterator, r):291+ """Stream decodes a iterator."""292+ encoding = get_encoding_from_headers(r.headers)293+ if encoding is None:294+ for item in iterator:295+ yield item296+ return297+298+ decoder = codecs.getincrementaldecoder(encoding)(errors='replace')299+ for chunk in iterator:300+ rv = decoder.decode(chunk)301+ if rv:302+ yield rv303+ rv = decoder.decode('', final=True)304+ if rv:305+ yield rv306+307+308+def get_unicode_from_response(r):309+ """Returns the requested content back in unicode.310+311+ :param r: Response object to get unicode content from.312+313+ Tried:314+315+ 1. charset from content-type316+317+ 2. every encodings from ``<meta ... charset=XXX>``318+319+ 3. fall back and replace all unicode characters320+321+ """322+323+ tried_encodings = []324+325+ # Try charset from content-type326+ encoding = get_encoding_from_headers(r.headers)327+328+ if encoding:329+ try:330+ return unicode(r.content, encoding)331+ except UnicodeError:332+ tried_encodings.append(encoding)333+334+ # Fall back:335+ try:336+ return unicode(r.content, encoding, errors='replace')337+ except TypeError:338+ return r.content339+340+341+def decode_gzip(content):342+ """Return gzip-decoded string.343+344+ :param content: bytestring to gzip-decode.345+ """346+347+ return zlib.decompress(content, 16 + zlib.MAX_WBITS)348+349+350+def stream_decode_gzip(iterator):351+ """Stream decodes a gzip-encoded iterator"""352+ try:353+ dec = zlib.decompressobj(16 + zlib.MAX_WBITS)354+ for chunk in iterator:355+ rv = dec.decompress(chunk)356+ if rv:357+ yield rv358+ buf = dec.decompress('')359+ rv = buf + dec.flush()360+ if rv:361+ yield rv362+ except zlib.error:363+ passmodified:.gitignore+1 added
5 unmodified lines6 *.pyc7 docs/_build8 toy.py9 .gitignore10+junit-report.xmlmodified:AUTHORS+7 added
38 unmodified lines39 - Shrikant Sharat Kandula40 - Mikko Ohtamaa41 - Den Shabalin42 - Daniel Miller <danielm@vs-networks.com>43+- Alejandro Giacometti44+- Rick Mak45+- Johan Bergström46+- Josselin Jacquard47+- Travis N. Vaught48+- Fredrik Möllerstrand49+- Daniel Hengevelddeleted:AUTHORS.orig-40 removed
1-Requests is written and maintained by Kenneth Reitz and2-various contributors:3-4-Development Lead5-````````````````6-7-- Kenneth Reitz <me@kennethreitz.com>8-9-10-Patches and Suggestions11-```````````````````````12-13-- Various Pocoo Members14-- Chris Adams15-- Flavio Percoco Premoli16-- Dj Gilcrease17-- Justin Murphy18-- Rob Madole19-- Aram Dulyan20-- Johannes Gorset21-- 村山めがね (Megane Murayama)22-- James Rowe23-- Daniel Schauenberg24-- Zbigniew Siciarz25-- Daniele Tricoli 'Eriol'26-- Richard Boulton27-- Miguel Olivares <miguel@moliware.com>28-- Alberto Paro29-- Jérémy Bethmont30-- 潘旭 (Xu Pan)31-- Tamás Gulácsi32-- Rubén Abad33-- Peter Manser34-- Jeremy Selie35-<<<<<<< HEAD36-- Jens Diemer37-- Alex <@alopatin>38-=======39-- Tom Hogans <tomhsx@gmail.com>40->>>>>>> 0ed641a26ec2200de00e4bbf3d170c767375351edeleted:HACKING-15 removed
1-Where possible, please follow PEP8 with regard to coding style. Sometimes the2-line length restriction is too hard to follow, so don't bend over backwards3-there.4-5-Triple-quotes should always be """, single quotes are ' unless using " would6-result in less escaping within the string.7-8-All modules, functions, and methods should be well documented reStructuredText9-for Sphinx AutoDoc.10-11-All functionality should be available in pure Python. Optional C (via Cython)12-implementations may be written for performance reasons, but should never13-replace the Python implementation.14-15-Lastly, don't take yourself too seriously :)modified:HISTORY.rst+58 added
1 History2 -------3 4+0.7.2 (2011-10-23)5+++++++++++++++++++6 7+* PATCH Fix.8+9+10+0.7.1 (2011-10-23)11+++++++++++++++++++12+13+* Move away from urllib2 authentication handling.14+* Fully Remove AuthManager, AuthObject, &c.15+* New tuple-based auth system with handler callbacks.16+17+18+0.7.0 (2011-10-22)19+++++++++++++++++++20+21+* Sessions are now the primary interface.22+* Deprecated InvalidMethodException.23+* PATCH fix.24+* New config system (no more global settings).25+26+27+0.6.6 (2011-10-19)28+++++++++++++++++++29+30+* Session parameter bugfix (params merging).31+32+33+0.6.5 (2011-10-18)34+++++++++++++++++++35+36+* Offline (fast) test suite.37+* Session dictionary argument merging.38+39+40+0.6.4 (2011-10-13)41+++++++++++++++++++42+43+* Automatic decoding of unicode, based on HTTP Headers.44+* New ``decode_unicode`` setting.45+* Removal of ``r.read/close`` methods.46+* New ``r.faw`` interface for advanced response usage.*47+* Automatic expansion of parameterized headers.48+49+50+0.6.3 (2011-10-13)51+++++++++++++++++++52+53+* Beautiful ``requests.async`` module, for making async requests w/ gevent.54+55+56+0.6.2 (2011-10-09)57+++++++++++++++++++58+59+* GET/HEAD obeys allow_redirects=False.60+61+62 0.6.1 (2011-08-20)63 ++++++++++++++++++64 65 * Enhanced status codes experience ``\o/``18 unmodified lines84 * HTTPError handling improvements85 * Improved https testing86 * Bugfixes87 88+89 0.5.1 (2011-07-23)90 ++++++++++++++++++91 92 * International Domain Name Support!127 unmodified linesadded:Makefile+16 added
1+init:2+ pip install -r reqs.txt3+4+test:5+ nosetests test_requests.py6+7+ci: init8+ nosetests test_requests.py --with-xunit --xunit-file=junit-report.xml9+10+stats:11+ pyflakes requests | awk -F\: '{printf "%s:%s: [E]%s\n", $1, $2, $3}' > violations.pyflakes.txt12+13+site:14+ cd docs; make dirhtml15+16+docs: sitemodified:MANIFEST.in+1 added-1 removed
1-include README.rst LICENSE HISTORY.rst 1+include README.rst LICENSE HISTORY.rst test_requests.pymodified:README.rst+9 added-13 removed
32 unmodified lines33 34 Features35 --------36 37-- Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests38- + Simple HTTP Header Request Attachment39- + Simple Data/Params Request Attachment40- + Simple Multipart File Uploads41- + CookieJar Support42- + Redirection History43- + Proxy Support44- + Redirection Recursion Urllib Fix45- + Auto Decompression of GZipped Content46- + Unicode URL Support37+- Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests.38+- Gevent support for Asyncronous Requests.39+- Sessions with cookie persistience.40+- Basic, Digest, and Custom Authentication support.41+- Automatic form-encoding of dictionaries42+- A simple dictionary interface for request/response cookies.43+- Multipart file uploads.44+- Automatc decoding of Unicode, gzip, and deflate responses.45+- Full support for unicode URLs and domain names.46 48-- Simple Authentication49- + Simple URL + HTTP Auth Registry47 51-48 Usage49 -----50 51 It couldn't be simpler. ::49 unmodified linesadded:reqs.txt+7 added
1+envoy==0.0.22+httpbin==0.0.43+gunicorn4+nose5+pyflakes6+omnijson7+rudolfmodified:test_requests.py+112 added-72 removed
1 unmodified line2 # -*- coding: utf-8 -*-3 4 from __future__ import with_statement5 6-import unittest6+import time7 import cookielib8+import os9+import unittest10 11+import requests12+import envoy13+14 try:15 import omnijson as json16 except ImportError:17 import json18 14-import requests19 16-from requests.sessions import Session20+# TODO: Detect an open port.21+PORT = os.environ.get('HTTPBIN_PORT', '7077')22 23+HTTPBIN_URL = 'http://0.0.0.0:%s/' % (PORT)24+# HTTPBIN_URL = 'http://127.0.0.1:8000/'25 19-HTTPBIN_URL = 'http://httpbin.org/'20-HTTPSBIN_URL = 'https://httpbin.ep.io/'26 22-# HTTPBIN_URL = 'http://staging.httpbin.org/'23-# HTTPSBIN_URL = 'https://httpbin-staging.ep.io/'24-25-27 def httpbin(*suffix):28 """Returns url for HTTPBIN resource."""29 30 return HTTPBIN_URL + '/'.join(suffix)31 32 32-def httpsbin(*suffix):33- """Returns url for HTTPSBIN resource."""33+SERVICES = (httpbin, )34 35- return HTTPSBIN_URL + '/'.join(suffix)35+_httpbin = False36 37+class RequestsTestSuite(unittest.TestCase):38+ """Requests test cases."""39 38-SERVICES = (httpbin, httpsbin)40+ # It goes to eleven.41+ _multiprocess_can_split_ = True42 43+ def setUp(self):44 45+ global _httpbin46 42-class RequestsTestSuite(unittest.TestCase):43- """Requests test cases."""47+ if not _httpbin:48 49+ c = envoy.connect('gunicorn httpbin:app --bind=0.0.0.0:%s' % (PORT))50 46- def setUp(self):47- pass51+ self.httpbin = c52+ _httpbin = True53+ time.sleep(1)54 55 56+57 def tearDown(self):58 """Teardown."""52- pass59+ # self.httpbin.kill()60 61+ def test_entry_points(self):62+ import requests63 64+ requests.session65+ requests.session().get66+ requests.session().head67+ requests.get68+ requests.head69+ requests.put70+ requests.patch71+ requests.post72+73+74+75 def test_invalid_url(self):76 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')77 58-78 def test_HTTP_200_OK_GET(self):60- r = requests.get(httpbin('/'))79+ r = requests.get(httpbin('/get'))80 self.assertEqual(r.status_code, 200)81 63-64- def test_HTTPS_200_OK_GET(self):65- r = requests.get(httpsbin('/'))82+ def test_HTTP_302_ALLOW_REDIRECT_GET(self):83+ r = requests.get(httpbin('redirect', '1'))84 self.assertEqual(r.status_code, 200)85 86+ def test_HTTP_302_GET(self):87+ r = requests.get(httpbin('redirect', '1'), allow_redirects=False)88+ self.assertEqual(r.status_code, 302)89 90+91 def test_HTTP_200_OK_GET_WITH_PARAMS(self):92 heads = {'User-agent': 'Mozilla/5.0'}93 94 r = requests.get(httpbin('user-agent'), headers=heads)29 unmodified lines124 self.assertTrue(heads['user-agent'] in r.content)125 126 127 def test_HTTP_200_OK_HEAD(self):106- r = requests.head(httpbin('/'))128+ r = requests.head(httpbin('/get'))129 self.assertEqual(r.status_code, 200)130 131 110- def test_HTTPS_200_OK_HEAD(self):111- r = requests.head(httpsbin('/'))112- self.assertEqual(r.status_code, 200)113-114-132 def test_HTTP_200_OK_PUT(self):133 r = requests.put(httpbin('put'))134 self.assertEqual(r.status_code, 200)135 136 120- def test_HTTPS_200_OK_PUT(self):121- r = requests.put(httpsbin('put'))122- self.assertEqual(r.status_code, 200)123-124-137 def test_HTTP_200_OK_PATCH(self):138 r = requests.patch(httpbin('patch'))139 self.assertEqual(r.status_code, 200)140 141 130- def test_HTTPS_200_OK_PATCH(self):131- r = requests.patch(httpsbin('patch'))132- self.assertEqual(r.status_code, 200)142+ def test_BASICAUTH_HTTP_200_OK_GET(self):143 134-135- def test_AUTH_HTTP_200_OK_GET(self):136-144 for service in SERVICES:145 146 auth = ('user', 'pass')147 url = service('basic-auth', 'user', 'pass')148 149 r = requests.get(url, auth=auth)143- # print r.__dict__150 self.assertEqual(r.status_code, 200)151 146-152 r = requests.get(url)153+ self.assertEqual(r.status_code, 401)154+155+156+ s = requests.session(auth=auth)157+ r = s.get(url)158 self.assertEqual(r.status_code, 200)159 160 161+ def test_DIGESTAUTH_HTTP_200_OK_GET(self):162+163+ for service in SERVICES:164+165+ auth = ('digest', 'user', 'pass')166+ url = service('digest-auth', 'auth', 'user', 'pass')167+168+ r = requests.get(url, auth=auth)169+ self.assertEqual(r.status_code, 200)170+171+ r = requests.get(url)172+ self.assertEqual(r.status_code, 401)173+174+175+ s = requests.session(auth=auth)176+ r = s.get(url)177+ self.assertEqual(r.status_code, 200)178+179 def test_POSTBIN_GET_POST_FILES(self):180 181 for service in SERVICES:182 41 unmodified lines224 225 r = requests.get(service('status', '500'))226 self.assertEqual(bool(r), False)227 200- r = requests.get(service('/'))228+ r = requests.get(service('/get'))229 self.assertEqual(bool(r), True)230 231 232 def test_request_ok_set(self):42 unmodified lines275 def test_unicode_get(self):276 277 for service in SERVICES:278 251- url = service('/')279+ url = service('/get')280 281 requests.get(url, params={'foo': u'føø'})282 requests.get(url, params={u'føø': u'føø'})283 requests.get(url, params={'føø': 'føø'})9 unmodified lines293 r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)294 self.assertEquals(r.status_code, 401)295 296 269- def test_settings(self):270-271- def test():272- r = requests.get(httpbin(''))273- r.raise_for_status()274-275- with requests.settings(timeout=0.0000001):276- self.assertRaises(requests.Timeout, test)277-278- with requests.settings(timeout=100):279- requests.get(httpbin(''))280-281-297 def test_urlencoded_post_data(self):298 299 for service in SERVICES:300 90 unmodified lines391 self.assertEquals(rbody.get('form'), None)392 self.assertEquals(rbody.get('data'), 'foobar')393 394 380- def test_idna(self):381- r = requests.get(u'http://➡.ws/httpbin')382- assert 'httpbin' in r.url395+ # def test_idna(self):396+ # r = requests.get(u'http://➡.ws/httpbin')397+ # assert 'httpbin' in r.url398 399 400 def test_urlencoded_get_query_multivalued_param(self):401 72 unmodified lines474 475 476 def test_session_HTTP_200_OK_GET(self):477 463- s = Session()464- r = s.get(httpbin('/'))478+ s = requests.session()479+ r = s.get(httpbin('/get'))480 self.assertEqual(r.status_code, 200)481 482 468- def test_session_HTTPS_200_OK_GET(self):469-470- s = Session()471- r = s.get(httpsbin('/'))472- self.assertEqual(r.status_code, 200)473-474-483 def test_session_persistent_headers(self):484 485 heads = {'User-agent': 'Mozilla/5.0'}486 479- s = Session()487+ s = requests.session()488 s.headers = heads489+490 # Make 2 requests from Session object, should send header both times491 r1 = s.get(httpbin('user-agent'))483-492 assert heads['User-agent'] in r1.content485- r2 = s.get(httpbin('user-agent'))493 494+ r2 = s.get(httpbin('user-agent'))495 assert heads['User-agent'] in r2.content496+497+ new_heads = {'User-agent': 'blah'}498+ r3 = s.get(httpbin('user-agent'), headers=new_heads)499+ assert new_heads['User-agent'] in r3.content500+501 self.assertEqual(r2.status_code, 200)502 503 504+ def test_session_persistent_params(self):505 506+ params = {'a': 'a_test'}507+508+ s = requests.session()509+ s.params = params510+511+ # Make 2 requests from Session object, should send header both times512+ r1 = s.get(httpbin('get'))513+ assert params['a'] in r1.content514+515+516+ params2 = {'b': 'b_test'}517+518+ r2 = s.get(httpbin('get'), params=params2)519+ assert params['a'] in r2.content520+ assert params2['b'] in r2.content521+522+523+ params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}524+525+ r3 = s.get(httpbin('get'), params=params3)526+527+ assert not params['a'] in r3.content528+ assert params3['b'] in r3.content529+ assert params3['c'] in r3.content530+531+532 if __name__ == '__main__':533 unittest.main()deleted:tox.ini-8 removed
1-[tox]2-envlist = py25,py26,py273-4-[testenv]5-commands=py.test --junitxml=junit-{envname}.xml6-deps =7- pytest8- omnijson