Skip to content
Myr

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

43 files+1424 added−916 removed

deleted:debian/changelog-5 removed
1python-requests (0.4.1-0) testing; urgency=low23 * Initial Debian package45 -- Bruno Clermont <bruno.clermont@gmail.com> Thu, 26 May 2011 16:25:00 -0500
deleted:debian/compat-1 removed
15
deleted:debian/control-13 removed
1Source: python-requests2Section: python3Priority: optional4Maintainer: Bruno Clermont <bruno.clermont@gmail.com>5Homepage: https://github.com/bclermont/requests6Bugs: https://github.com/bclermont/requests/issues7Build-Depends: debhelper, python-support89Package: python-requests10Architecture: all11Depends: ${python:Depends}, python-support12Provides: ${python:Provides}13Description: Python HTTP Requests for Humans.
deleted:debian/docs-1 removed
1docs/user/*.rst
deleted:debian/pyversions-1 removed
12.4-
deleted:debian/rules-42 removed
1#!/usr/bin/make -f23# Verbose mode4#export DH_VERBOSE=156clean:7 dh_testdir8 dh_testroot910 rm -rf build requests.egg-info11# find django-sentry/ -name *.pyc | xargs rm -f1213 dh_clean1415build:16 dh_testdir1718 python setup.py build1920install:21 dh_testdir22 dh_installdirs2324 python setup.py install --root $(CURDIR)/debian/python-requests2526binary-indep: install2728binary-arch: install29 dh_install30 dh_installdocs31# dh_installchangelogs32 dh_compress33 dh_fixperms34 dh_pysupport35 dh_gencontrol36 dh_installdeb37 dh_md5sums38 dh_builddeb -- -Z lzma -z93940binary: binary-indep binary-arch41.PHONY: build clean binary-indep binary-arch binary42
modified:docs/community/faq.rst+1 added-1 removed
7 unmodified lines
8Encoded Data?9-------------1011Requests automatically decompresses gzip-encoded responses, and does12its best to decodes response content to unicode when possible.12its best to decode response content to unicode when possible.1314You can get direct access to the raw response (and even the socket),15if needed as well.16
67 unmodified lines
added:docs/community/out-there.rst+63 added
1Modules2=======34- `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.1011Articles & 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/>`_192021Integrations22============2324ScraperWiki25------------2627`ScraperWiki <https://scraperwiki.com/>`_ is an excellent service that allows28you to run Python, Ruby, and PHP scraper scripts on the web. Now, Requests29v0.6.1 is available to use in your scrapers!3031To give it a try, simply::3233 import requests343536Managed Packages37================3839Requests is available in a number of popular package formats. Of course,40the ideal way to install Requests is via The Cheeseshop.414243Ubuntu & Debian44---------------4546Requests is available installed as a Debian package! Debian Etch Ubuntu, since Oneiric::4748 $ apt-get install python-requests4950Unfortunately, the most recent version available is v0.5.0. If you're on the51Debian Python Package team, I'd love an update of that :)525354Fedora and RedHat55-----------------5657You can easily install Requests v0.6.1 with yum on rpm-based systems::5859 $ yum install python-requests60616263
modified:docs/community/support.rst+1 added-1 removed
1 unmodified line
23Support4=======56If you have a questions or issues about Requests, there are serveral options:6If you have a questions or issues about Requests, there are several options:78Send a Tweet9------------10
27 unmodified lines
modified:docs/community/updates.rst+1 added-1 removed
2 unmodified lines
3Updates4=======56If you'd like to stay up to date on the community and development of Requests,7there are serveral options:7there are several options:89GitHub10------11
19 unmodified lines
modified:docs/user/advanced.rst+75 added-7 removed
15 unmodified lines
16A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920 with requests.session() as s:20 s = requests.session()2122 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")2425 print r.content26 # '{"cookies": {"sessioncookie": "123456789"}}'25 print r.content26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods::30
7 unmodified lines
383940.. admonition:: Global Settings4142 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).444546Asynchronous Requests47----------------------4849Requests has first-class support for non-blocking i/o requests, powered50by gevent. This allows you to send a bunch of HTTP requests at the same5152First, let's import the async module. Heads up — if you don't have53`gevent <gevent>`_ this will fail::5455 from requests import async5657The ``async`` module has the exact same api as ``requests``, except it58doesn't send the request immediately. Instead, it returns the ``Request``59object.6061We can build a list of ``Request`` objects easily::6263 urls = [64 'http://python-requests.org',65 'http://httpbin.org',66 'http://python-guide.org',67 'http://kennethreitz.com'68 ]6970 rs = [async.get(u) for u in urls]7172Now we have a list of ``Request`` objects, ready to be sent. We could send them73one at a time with ``Request.send()``, but that would take a while. Instead,74we'll send them all at the same time with ``async.map()``. Using ``async.map()``75will also guarantee execution of the ``response`` hook, described below. ::7677 >>> async.map(rs)78 [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]798081Event Hooks82-----------8384Requests has a hook system that you can use to manipulate portions of
71 unmodified lines
156 }157 }158159160Custom Authentication161---------------------162163Requests allows you to use specify your own authentication mechanism.164165When you pass our authentication tuple to a request method, the first166string is the type of authentication. 'basic' is inferred if none is167provided.168169You can pass in a callable object instead of a string for the first item170in the tuple, and it will be used in place of the built in authentication171callbacks.172173Let'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.175176We simply need to define a callback function that will be used to update the177Request object, right before it is dispatched.178179::180181 def pizza_auth(r, username):182 """Attaches HTTP Pizza Authentication to the given Request object.183 """184 r.headers['X-Pizza'] = username185186 return r187188Then, we can make a request using our Pizza Auth::189190 >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))191 <Response [200]>192193194Verbose Logging195---------------196197If you want to get a good look at what HTTP requests are being sent
8 unmodified lines
modified:docs/user/install.rst+23 added-1 removed
16 unmodified lines
17or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::1819 $ easy_install requests2021But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install>`_.22232425Cheeseshop Mirror
27 unmodified lines
53Once you have a copy of the source, you can embed it in your Python package,54or install it into your site-packages easily::5556 $ python setup.py install5758.. _gevent:5960Installing Gevent61-----------------6263If you are using the ``requests.async`` module for making concurrent64requests, you need to install gevent.6566To install gevent, you'll need ``libevent``.6768OSX::6970 $ brew install libevent7172Ubuntu::7374 $ apt-get install libevent-dev7576Once you have ``libevent``, you can install ``gevent`` with ``pip``::7778 $ pip install gevent
modified:docs/user/intro.rst-2 removed
45 unmodified lines
46 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.4748 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.495051
modified:docs/user/quickstart.rst+29 added
134 unmodified lines
135136 >>> r = requests.get(url, cookies=cookies)137 >>> r.content138 '{"cookies": {"cookies_are": "working"}}'139140141Basic Authentication142--------------------143144Most web services require authentication. There many different types of145authentication, but the most common is called HTTP Basic Auth.146147Making requests with Basic Auth is easy, with Requests::148149 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))150 <Response [200]>151152153Digest Authentication154---------------------155156Another popular form of protecting web service is Digest Authentication.157158Requests supports it!::159160 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'161 >>> requests.get(url, auth=('digest', 'user', 'pass'))162 <Response [200]>163164165-----------------------166167Ready for more? Check out the advanced_ section.
modified:docs/api.rst+15 added-3 removed
29 unmodified lines
3031.. autoclass:: Response32 :inherited-members:3334Async35-----3637.. module:: requests.async383940.. autofunction:: map41.. autofunction:: request42.. autofunction:: head43.. autofunction:: get44.. autofunction:: post45.. autofunction:: put46.. autofunction:: patch47.. autofunction:: delete48495051Utilities52---------5354These functions are used internally, but may be useful outside of
7 unmodified lines
62.. autofunction:: dict_from_cookiejar63.. autofunction:: cookiejar_from_dict64.. autofunction:: add_dict_to_cookiejar6551Curl52~~~~53.. autofunction:: curl_from_request6667Encodings68~~~~~~~~~69
36 unmodified lines
modified:docs/index.rst+2 added
39 unmodified lines
40------------4142`Twitter, Inc <http://twitter.com>`_,43a U.S. Federal Institution,44NIH, 45`Readability <http://readability.com>`_, and46`Work for Pie <http://workforpie.com>`_47use Requests internally.48
38 unmodified lines
87.. toctree::88 :maxdepth: 28990 community/faq91 community/out-there.rst92 community/support93 community/updates9495API Documentation
23 unmodified lines
modified:requests/__init__.py+31 added-2 removed
1# -*- coding: utf-8 -*-23from core import *4from core import __version__3# __4# /__) _ _ _ _ _/ _5# / ( (- (/ (/ (- _) / _)6# /78"""9requests10~~~~~~~~1112:copyright: (c) 2011 by Kenneth Reitz.13:license: ISC, see LICENSE for more details.1415"""1617__title__ = 'requests'18__version__ = '0.7.2'19__build__ = 0x00070220__author__ = 'Kenneth Reitz'21__license__ = 'ISC'22__copyright__ = 'Copyright 2011 Kenneth Reitz'232425from . import utils26from .models import HTTPError, Request, Response27from .api import request, get, head, post, patch, put, delete28from .sessions import session29from .status_codes import codes30from .exceptions import (31 RequestException, AuthenticationError, Timeout, URLRequired,32 TooManyRedirects33)
modified:requests/api.py+30 added-114 removed
2 unmodified lines
3"""4requests.api5~~~~~~~~~~~~67This module impliments the Requests API.7This module implements the Requests API.89:copyright: (c) 2011 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1314import config15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict14from .sessions import session1520from urlparse import urlparse2116__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')171819def 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):3228 """Constructs and sends a :class:`Request <models.Request>`.29 Returns :class:`Response <models.Response>` object.3031 :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 """4344 if cookies is None:45 cookies = {}4647 cookies = cookiejar_from_dict(cookies)4849 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 )3963 # Arguments manipulation hook.64 args = dispatch_hook('args', hooks, args)4066 r = Request(**args)4168 # Pre-request hook.69 r = dispatch_hook('pre_request', hooks, r)7071 # Send the HTTP Request.72 r.send()7374 # Post-request hook.75 r = dispatch_hook('post_request', hooks, r)7677 # Response manipulation hook.78 r.response = dispatch_hook('response', hooks, r.response)7980 return r.response818242def get(url, **kwargs):8443 """Sends a GET request. Returns :class:`Response` object.4445 :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 """4849 kwargs.setdefault('allow_redirects', True)50 return request('GET', url, **kwargs)515253def head(url, **kwargs):10254 """Sends a HEAD request. Returns :class:`Response` object.5556 :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 """5960 kwargs.setdefault('allow_redirects', True)61 return request('HEAD', url, **kwargs)626364def post(url, data='', **kwargs):12065 """Sends a POST request. Returns :class:`Response` object.6667 :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 """71135 return request('POST', url, data=data, **kwargs)72 return request('post', url, data=data, **kwargs)737475def put(url, data='', **kwargs):76 """Sends a PUT request. Returns :class:`Response` object.7778 :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 """82153 return request('PUT', url, data=data, **kwargs)83 return request('put', url, data=data, **kwargs)848586def patch(url, data='', **kwargs):87 """Sends a PATCH request. Returns :class:`Response` object.8889 :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 """93171 return request('PATCH', url, **kwargs)94 return request('patch', url, data=data, **kwargs)959697def delete(url, **kwargs):17598 """Sends a DELETE request. Returns :class:`Response` object.99100 :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 """103188 return request('DELETE', url, **kwargs)104 return request('delete', url, **kwargs)
modified:requests/async.py+62 added-25 removed
1# -*- coding: utf-8 -*-23"""4 requests.async5 ~~~~~~~~~~~~~~4requests.async5~~~~~~~~~~~~~~67 This module implements the main Requests system, after monkey-patching8 the urllib2 module with eventlet or gevent..910 :copyright: (c) 2011 by Kenneth Reitz.11 :license: ISC, see LICENSE for more details.7This module contains an asynchronous replica of ``requests.api``, powered8by gevent. All API methods return a ``Request`` instance (as opposed to9``Response``). A list of requests can be sent with ``map()``.10"""1112try:13 import gevent14 from gevent import monkey as curious_george15except ImportError:16 raise RuntimeError('Gevent is required for requests.async.')1715from __future__ import absolute_import18# Monkey-patch.19curious_george.patch_all(thread=False)2017import urllib18import urllib221from . import api22from .hooks import dispatch_hook2320from urllib2 import HTTPError2425__all__ = (26 'map',27 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'28)2923try:24 import eventlet25 eventlet.monkey_patch()26except ImportError:27 pass3029if not 'eventlet' in locals():30 try:31 from gevent import monkey32 monkey.patch_all()33 except ImportError:34 pass31def patched(f):32 """Patches a given API function to not send."""3334 def wrapped(*args, **kwargs):35 return f(*args, return_response=False, **kwargs)3637if not 'eventlet' in locals():38 raise ImportError('No Async adaptations of urllib2 found!')37 return wrapped383941from .core import *40def send(r, pools=None):41 """Sends a given Request object."""4243 if pools:44 r._pools = pools4546 r.send()4748 return r.response495051# Patched requests.api functions.52get = patched(api.get)53head = patched(api.head)54post = patched(api.post)55put = patched(api.put)56patch = patched(api.patch)57delete = patched(api.delete)58request = patched(api.request)596061def map(requests, prefetch=True):62 """Concurrently converts a list of Requests to Responses.6364 :param requests: a collection of Request objects.65 :param prefetch: If False, the content will not be downloaded immediately.66 """6768 jobs = [gevent.spawn(send, r) for r in requests]69 gevent.joinall(jobs)7071 if prefetch:72 [r.response.content for r in requests]7374 return [r.response for r in requests]75767778
added:requests/auth.py+151 added
1# -*- coding: utf-8 -*-23"""4requests.auth5~~~~~~~~~~~~~67This module contains the authentication handlers for Requests.8"""910import time11import hashlib1213from base64 import b64encode14from urlparse import urlparse1516from .utils import randombytes, parse_dict_header171819def http_basic(r, username, password):20 """Attaches HTTP Basic Authentication to the given Request object.21 Arguments should be considered non-positional.2223 """24 username = str(username)25 password = str(password)2627 auth_s = b64encode('%s:%s' % (username, password))28 r.headers['Authorization'] = ('Basic %s' % auth_s)2930 return r313233def http_digest(r, username, password):34 """Attaches HTTP Digest Authentication to the given Request object.35 Arguments should be considered non-positional.36 """3738 def handle_401(r):39 """Takes the given response and tries digest-auth, if needed."""4041 s_auth = r.headers.get('www-authenticate', '')4243 if 'digest' in s_auth.lower():4445 last_nonce = ''46 nonce_count = 04748 chal = parse_dict_header(s_auth.replace('Digest ', ''))4950 realm = chal['realm']51 nonce = chal['nonce']52 qop = chal.get('qop')53 algorithm = chal.get('algorithm', 'MD5')54 opaque = chal.get('opaque', None)5556 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))6465 if H is None:66 return None6768 # XXX not implemented yet69 entdig = None70 path = urlparse(r.request.url).path7172 A1 = "%s:%s:%s" % (username, realm, password)73 A2 = "%s:%s" % (r.request.method, path)7475 if qop == 'auth':76 if nonce == last_nonce:77 nonce_count += 178 else:79 nonce_count = 180 last_nonce = nonce8182 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 None9495 # 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)105106107 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_code112113 # r.request.response114115 print locals()116117 print _r.headers118 return _r119120 return r121122 r.hooks['response'] = handle_401123 return r124125126def dispatch(t):127 """Given an auth tuple, return an expanded version."""128129 if not t:130 return t131 else:132 t = list(t)133134 # Make sure they're passing in something.135 assert len(t) >= 2136137 # If only two items are passed in, assume HTTPBasic.138 if (len(t) == 2):139 t.insert(0, 'basic')140141 # 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_digest147148 # Return a custom callable.149 return (t[0], tuple(t[1:]))150151
deleted:requests/config.py-67 removed
1# -*- coding: utf-8 -*-23"""4requests.config5~~~~~~~~~~~~~~~67This module provides the Requests settings feature set.89"""1011class Settings(object):12 _singleton = {}1314 # attributes with defaults15 __attrs__ = []1617 def __init__(self, **kwargs):18 super(Settings, self).__init__()1920 self.__dict__ = self._singleton212223 def __call__(self, *args, **kwargs):24 # new instance of class to call25 r = self.__class__()2627 # cache previous settings for __exit__28 r.__cache = self.__dict__.copy()29 map(self.__cache.setdefault, self.__attrs__)3031 # set new settings32 self.__dict__.update(*args, **kwargs)3334 return r353637 def __enter__(self):38 pass394041 def __exit__(self, *args):4243 # restore cached copy44 self.__dict__.update(self.__cache.copy())45 del self.__cache464748 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)555657settings = Settings()5859settings.base_headers = {'User-Agent': 'python-requests.org'}60settings.accept_gzip = True61settings.proxies = None62settings.verbose = None63settings.timeout = None64settings.max_redirects = 306566#: Use socket.setdefaulttimeout() as fallback?67settings.timeout_fallback = True
deleted:requests/core.py-27 removed
1# -*- coding: utf-8 -*-23"""4requests.core5~~~~~~~~~~~~~67This module implements the main Requests system.89:copyright: (c) 2011 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1314__title__ = 'requests'15__version__ = '0.6.1'16__build__ = 0x00060117__author__ = 'Kenneth Reitz'18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'202122from models import HTTPError23from api import *24from exceptions import *25from sessions import session26from status_codes import codes27from config import settings
added:requests/defaults.py+38 added
1# -*- coding: utf-8 -*-23"""4requests.defaults5~~~~~~~~~~~~~~~~~67This module provides the Requests configuration defaults.89settings parameters:1011- :base_headers: - Sets default User-Agent to `python-requests.org`12- :accept_gzip: - Whether or not to accept gzip-compressed data13- :proxies: - http proxies?14- :verbose: - display verbose information?15- :timeout: - timeout time until request terminates16- :max_redirects: - maximum number of allowed redirects?17- :decode_unicode: - whether or not to accept unicode?1819"""2021from . import __version__2223defaults = dict()242526defaults['base_headers'] = {27 'User-Agent': 'python-requests/%s' % __version__,28 'Accept-Encoding': ', '.join(('identity', 'deflate', 'compress', 'gzip')),29}3031defaults['proxies'] = {}32defaults['verbose'] = None33defaults['timeout'] = None34defaults['max_redirects'] = 3035defaults['decode_unicode'] = True36defaults['timeout_fallback'] = True37# defaults['keep_alive'] = True38# defaults['max_connections'] = 10
modified:requests/exceptions.py+5 added-6 removed
1# -*- coding: utf-8 -*-23"""4requests.exceptions5~~~~~~~~~~~~~~~5~~~~~~~~~~~~~~~~~~~67This module contains the set of Requests' exceptions.89"""1011class RequestException(Exception):10 """There was an ambiguous exception that occured while handling your12 """There was an ambiguous exception that occurred while handling your13 request."""1415class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15 1718class Timeout(RequestException):19 """The request timed out."""2021class URLRequired(RequestException):22 """A valid URL is required to make a request."""2322class InvalidMethod(RequestException):23 """An inappropriate method was attempted."""2424class TooManyRedirects(RequestException):25 """Too many redirects."""
modified:requests/hooks.py+1 added-1 removed
24 unmodified lines
25import warnings262728def 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."""3031 hooks = hooks or dict()3233 if key in hooks:
7 unmodified lines
modified:requests/models.py+178 added-280 removed
12# -*- coding: utf-8 -*-34"""5requests.models
9 unmodified lines
15from urllib2 import HTTPError16from urlparse import urlparse, urlunparse, urljoin17from datetime import datetime1818from .config import settings19from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19from .hooks import dispatch_hook20from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers23from .utils import dict_from_cookiejar24from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects23from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)24from .status_codes import codes25from .exceptions import Timeout, URLRequired, TooManyRedirects26from .monkeys import Request as _Request27from .monkeys import HTTPRedirectHandler2829from .auth import dispatch as auth_dispatch3031REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)32333435class 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 """3940 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):5542 #: Float describ the timeout of the request.56 #: Float describes the timeout of the request.57 # (Use socket.setdefaulttimeout() as fallback)58 self.timeout = timeout5960 #: Request URL.61 self.url = url6249 #: 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 = headers6566 #: Dictionary of files to multipart upload (``{filename: content}``).67 self.files = files6855 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.69 #: HTTP Method to use.70 self.method = method7172 #: Dictionary or byte of request body data to attach to the59 #: :class:`Request <models.Request>`.73 #: :class:`Request <Request>`.74 self.data = None7576 #: Dictionary or byte of querystring data to attach to the63 #: :class:`Request <models.Request>`.77 #: :class:`Request <Request>`.78 self.params = None7966 #: 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 = redirect8384 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)
4 unmodified lines
8990 self.data, self._enc_data = self._encode_params(data)91 self.params, self._enc_params = self._encode_params(params)9279 #: :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()9683 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)9988 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89 self.auth = auth100 #: CookieJar to attach to :class:`Request <Request>`.101 self.cookies = cookies10291 #: CookieJar to attach to :class:`Request <models.Request>`.92 self.cookiejar = cookiejar103 #: Dictionary of configurations for this request.104 self.config = config105106 #: True if Request has been sent.107 self.sent = False108109 #: Event-handling hooks.110 self.hooks = hooks11198 # Header manipulation and defaults.99100 if settings.accept_gzip:101 settings.base_headers.update({'Accept-Encoding': 'gzip'})102112 if headers:113 headers = CaseInsensitiveDict(self.headers)114 else:115 headers = CaseInsensitiveDict()116108 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] = v120121 self.headers = headers122123 # Pre-request hook.124 r = dispatch_hook('pre_request', hooks, self)125 self.__dict__.update(r.__dict__)126127128 def __repr__(self):129 return '<Request [%s]>' % (self.method)130131119 def _checks(self):120 """Deterministic checks for consistency."""121122 if not self.url:123 raise URLRequired124125132 def _get_opener(self):133 """Creates appropriate opener object for urllib2."""134135 _handlers = []136131 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))139134 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)140141 _handlers.append(self.auth.handler)142140 if self.proxies:141 _handlers.append(urllib2.ProxyHandler(self.proxies))142143 _handlers.append(HTTPRedirectHandler)
18 unmodified lines
162 return opener.open163164165 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 """169170171 def build(resp):172173 response = Response()174 response.config = self.config175 response.status_code = getattr(resp, 'code', None)176177 try:178 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))178 response.read = resp.read179 response._resp = resp180 response._close = resp.close179 response.raw = resp180182 if self.cookiejar:181 if self.cookies:182 response.cookies = dict_from_cookiejar(self.cookies)183184 response.cookies = dict_from_cookiejar(self.cookiejar)184186185 except AttributeError:186 pass187188 if is_error:
14 unmodified lines
203 ('location' in r.headers) and204 ((r.status_code is codes.see_other) or (self.allow_redirects))205 ):206209 r.close()207 r.raw.close()208211 if not len(history) < settings.max_redirects:209 if not len(history) < self.config.get('max_redirects'):210 raise TooManyRedirects()211212 history.append(r)213
15 unmodified lines
229 else:230 method = self.method231232 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 lines
259 version of that.260261 Otherwise, assumes the data is already encoded appropriately, and262 returns it twice.258263 """264265 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 lines
303 :param anyway: If True, request will be sent, even if it has304 already been sent.305 """306302 self._checks()303 success = False307 # Some people...308 if not self.url:309 raise URLRequired310311 # 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 ))316311317 # Build the URL318 url = self._build_url()313 if self.method in ('GET', 'HEAD', 'DELETE'):314 req = _Request(url, method=self.method)319320 # Attach uploaded files.321 if self.files:322 register_openers()323324 # Add form-data to the multipart.325 if self.data:326 self.files.update(self.data)327328 data, headers = multipart_encode(self.files)329330 else:331 data = self._enc_data332 headers = {}333317 if self.files:318 register_openers()334 if self.auth:335 auth_func, auth_args = self.auth336320 if self.data:321 self.files.update(self.data)337 r = auth_func(self, *auth_args)338323 datagen, headers = multipart_encode(self.files)324 req = _Request(url, data=datagen, headers=headers, method=self.method)339 self.__dict__.update(r.__dict__)340326 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)343344 # 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 lines
358 # timeout argument is new since Python v2.6359 if not 'timeout' in str(err):360 raise361346 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)366367 resp = opener(req)368353 if settings.timeout_fallback:354 # restore gobal timeout369 if self.config.get('timeout_fallback'):370 # restore global timeout371 socket.setdefaulttimeout(old_timeout)372357 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)375376 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)382383 self._build_response(why, is_error=True)384367385 else:386 self._build_response(resp)387 self.response.ok = True388389390 self.sent = self.response.ok391375 return self.sent392 # Response manipulation hook.393 self.response = dispatch_hook('response', self.hooks, self.response)394395 # Post-request hook.396 r = dispatch_hook('post_request', self.hooks, self)397 self.__dict__.update(r.__dict__)398399 return self.sent400401402class 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 """408409 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.410411 self._content = None412 self._content_consumed = False413414 #: Integer Code of responded HTTP Status.415 self.status_code = None416417 #: 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()421422 #: File-like object representation of response (for advanced usage).423 self.raw = None424425 #: Final URL location of Response.426 self.url = None427399 #: True if no :attr:`error` occured.428 #: True if no :attr:`error` occurred.429 self.ok = False430401 #: Resulting :class:`HTTPError` of request, if one occured.431 #: Resulting :class:`HTTPError` of request, if one occurred.432 self.error = None433403 #: 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 = []438407 #: The Request that created the Response.439 #: The :class:`Request <Request>` that created the Response.440 self.request = None441442 #: A dictionary of Cookies the server sent back.443 self.cookies = None444445 #: Dictionary of configurations for this request.446 self.config = None447448449 def __repr__(self):450 return '<Response [%s]>' % (self.status_code)451452453 def __nonzero__(self):454 """Returns true if :attr:`status_code` is 'OK'."""455456 return not self.error457458 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')467422 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 gen483437 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 """489490 if self._content is not None:491 return self._content492443 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')496448class AuthManager(object):449 """Requests Authentication Manager."""497 # Read the contents.498 self._content = self.raw.read()499451 def __new__(cls):452 singleton = cls.__dict__.get('__singleton__')453 if singleton is not None:454 return singleton455456 cls.__singleton__ = singleton = object.__new__(cls)457458 return singleton459460461 def __init__(self):462 self.passwd = {}463 self._auth = {}464465466 def __repr__(self):467 return '<AuthManager [%s]>' % (self.method)468469470 def add_auth(self, uri, auth):471 """Registers AuthObject to AuthManager."""472473 uri = self.reduce_uri(uri, False)474475 # 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 pass506482 self._auth[uri] = auth507 # Decode unicode content.508 if self.config.get('decode_unicode'):509 self._content = get_unicode_from_response(self)510511 self._content_consumed = True512 return self._content513485 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]514491 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.error519493 if reduced_uri not in self.passwd:494 self.passwd[reduced_uri] = {}495 self.passwd[reduced_uri] = (user, passwd)496497498 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 authinfo504505 return (None, None)506507508 def get_auth(self, uri):509 (in_domain, in_path) = self.reduce_uri(uri, False)510511 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 authority517518519 def reduce_uri(self, uri, default_port=True):520 """Accept authority or URI and extract only the authority and path."""521522 # note HTTP URLs do not have a userinfo component523 parts = urllib2.urlparse.urlsplit(uri)524525 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 = '/'535536 host, port = urllib2.splitport(authority)537538 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)544545 return authority, path546547548 def is_suburi(self, base, test):549 """Check if test is below base in a URI tree550551 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 False561562563 def empty(self):564 self.passwd = {}565566567 def remove(self, uri, realm=None):568 # uri could be a single URI or a sequence569 if isinstance(uri, basestring):570 uri = [uri]571572 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]575576577 def __contains__(self, uri):578 # uri could be a single URI or a sequence579 if isinstance(uri, basestring):580 uri = [uri]581582 uri = tuple([self.reduce_uri(u, False) for u in uri])583584 if uri in self.passwd:585 return True586587 return False588589auth_manager = AuthManager()590591592593class 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.598599 :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 """604605 _handlers = {606 'basic': HTTPBasicAuthHandler,607 'forced_basic': HTTPForcedBasicAuthHandler,608 'digest': HTTPDigestAuthHandler,609 'proxy_basic': urllib2.ProxyBasicAuthHandler,610 'proxy_digest': urllib2.ProxyDigestAuthHandler611 }612613 def __init__(self, username, password, handler='forced_basic', realm=None):614 self.username = username615 self.password = password616 self.realm = realm617618 if isinstance(handler, basestring):619 self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)620 else:621 self.handler = handler
modified:requests/monkeys.py+5 added-114 removed
27 unmodified lines
282930class 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 pass3435 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 = _pass39373839class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):40 """HTTP Basic Auth Handler with authentication loop fixes."""4142 def __init__(self, *args, **kwargs):43 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44 self.retried_req = None45 self.retried = 0464748 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 pass535455 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 = 06061 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(62 self, auth_header, host, req, headers63 )64656667class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):68 """HTTP Basic Auth Handler with forced Authentication."""6970 auth_header = 'Authorization'71 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'72 'realm=(["\'])(.*?)\\2', re.I)7374 def __init__(self, *args, **kwargs):75 HTTPBasicAuthHandler.__init__(self, *args, **kwargs)767778 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 response8384 http_error_404 = http_error_401858687 def _http_error_auth_reqed(self, authreq, host, req, headers):8889 authreq = headers.get(authreq, None)9091 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 += 19798 if authreq:99100 mo = self.rx.search(authreq)101102 if mo:103 scheme, quote, realm = mo.groups()104105 if scheme.lower() == 'basic':106 response = self.retry_http_basic_auth(host, req, realm)107108 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')113114 if response and response.code not in (401, 404):115 self.retried = 0116 return response117118119120class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):121122 def __init__(self, *args, **kwargs):123 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)124 self.retried_req = None125126 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 pass131132 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.140141 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 raise
deleted:requests/patches.py-5 removed
1# -*- coding: utf-8 -*-23"""4requests.monkeys5"""
modified:requests/sessions.py+200 added-39 removed
1# -*- coding: utf-8 -*-23"""4requests.session5~~~~~~~~~~~~~~~5~~~~~~~~~~~~~~~~67This module provides a Session object to manage and persist settings across8requests (cookies, auth, proxies).910"""1112import cookielib1314from . import api15from .utils import add_dict_to_cookiejar14from .defaults import defaults15from .models import Request16from .hooks import dispatch_hook17from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand181920def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.2223 If a local key in the dictionary is set to None, it will be removed.24 """2526 if default_kwarg is None:27 return local_kwarg2829 if isinstance(local_kwarg, basestring):30 return local_kwarg3132 if local_kwarg is None:33 return default_kwarg3435 # Bypass if not a dictionary (e.g. timeout)36 if not hasattr(default_kwarg, 'items'):37 return local_kwarg3839 # Update new values.40 kwargs = default_kwarg.copy()41 kwargs.update(local_kwarg)4243 # Remove keys that are set to None.44 for (k,v) in local_kwarg.items():45 if v is None:46 del kwargs[k]4748 return kwargs495051class Session(object):52 """A Requests session."""5322 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']54 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params', 'config']555625 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):6667 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 {}7576 for (k, v) in defaults.items():77 self.config.setdefault(k, v)7879 # Set up a CookieJar to be used by default80 self.cookies = cookielib.FileCookieJar()8130 # 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())3334 # Map and wrap requests.api methods35 self._map_api_methods()363782 def __repr__(self):83 return '<requests-client at 0x%x>' % (id(self))8485 def __enter__(self):86 return self8788 def __exit__(self, *args):45 # print args89 pass9091 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):10449 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.107108 :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 """12255 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()12463 # 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 = {}12770 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)13073 return func(*args, **kwargs)74 return wrapper_func131 cookies = cookiejar_from_dict(cookies)13276 # 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)137138 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 )153154 for attr in self.__attrs__:155 session_val = getattr(self, attr, None)156 local_val = args.get(attr)157158 args[attr] = merge_kwargs(local_val, session_val)159160 # Arguments manipulation hook.161 args = dispatch_hook('args', hooks, args)162163 r = Request(**args)164165 # Don't send if asked nicely.166 if not return_response:167 return r168169 # Send the HTTP Request.170 r.send()171172173 return r.response174175176 def get(self, url, **kwargs):177 """Sends a GET request. Returns :class:`Response` object.178179 :param url: URL for the new :class:`Request` object.180 :param **kwargs: Optional arguments that ``request`` takes.181 """182183 kwargs.setdefault('allow_redirects', True)184 return self.request('GET', url, **kwargs)185186187 def head(self, url, **kwargs):188 """Sends a HEAD request. Returns :class:`Response` object.189190 :param url: URL for the new :class:`Request` object.191 :param **kwargs: Optional arguments that ``request`` takes.192 """193194 kwargs.setdefault('allow_redirects', True)195 return self.request('HEAD', url, **kwargs)196197198 def post(self, url, data='', **kwargs):199 """Sends a POST request. Returns :class:`Response` object.200201 :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 """205206 return self.request('post', url, data=data, **kwargs)207208209 def put(self, url, data='', **kwargs):210 """Sends a PUT request. Returns :class:`Response` object.211212 :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 """216217 return self.request('put', url, data=data, **kwargs)218219220 def patch(self, url, data='', **kwargs):221 """Sends a PATCH request. Returns :class:`Response` object.222223 :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 """227228 return self.request('patch', url, data='', **kwargs)229230231 def delete(self, url, **kwargs):232 """Sends a DELETE request. Returns :class:`Response` object.233234 :param url: URL for the new :class:`Request` object.235 :param **kwargs: Optional arguments that ``request`` takes.236 """237238 return self.request('delete', url, **kwargs)239240241242def session(**kwargs):82 """Returns a :class:`Session` for context-managment."""243 """Returns a :class:`Session` for context-management."""244245 return Session(**kwargs)
modified:requests/status_codes.py+5 added-2 removed
45 unmodified lines
46 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 lines
modified:requests/structures.py+1 added-1 removed
2 unmodified lines
3"""4requests.structures5~~~~~~~~~~~~~~~~~~~67Datastructures that power Requests.7Data structures that power Requests.89"""1011class CaseInsensitiveDict(dict):
54 unmodified lines
modified:requests/utils.py+296 added-5 removed
7 unmodified lines
8that are also useful for external consumption.910"""1112import cgi13import codecs14import cookielib15import os16import random17import re18import zlib1920from urllib2 import parse_http_list as _parse_list_header2115def dict_from_cookiejar(cookiejar):16 """Returns a key/value dictionary from a CookieJar."""2223# From mitsuhiko/werkzeug (used with permission).24def parse_list_header(value):25 """Parse lists as described by RFC 2068 Section 2.2627 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.3132 It basically works like :func:`parse_set_header` just that items33 may appear multiple times and case sensitivity is preserved.3435 The return value is a standard :class:`list`:3637 >>> parse_list_header('token, "quoted value"')38 ['token', 'quoted value']3940 To create a header from the :class:`list` again, use the41 :func:`dump_header` function.4243 :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 result525354# From mitsuhiko/werkzeug (used with permission).55def 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:5859 >>> 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')]6465 If there is no value for a key it will be `None`:6667 >>> parse_dict_header('key_without_value')68 {'key_without_value': None}6970 To create a header from the :class:`dict` again, use the71 :func:`dump_header` function.7273 :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 result868788# From mitsuhiko/werkzeug (used with permission).89def 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.9394 :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]102103 # 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 value111112113def header_expand(headers):114 """Returns an HTTP Header value string from a dictionary.115116 Example expansion::117118 {'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-c120121 (('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 """124125 collector = []126127 if isinstance(headers, dict):128 headers = headers.items()129130 elif isinstance(headers, basestring):131 return headers132133 for i, (value, params) in enumerate(headers):134135 _params = []136137 for (p_k, p_v) in params.items():138139 _params.append('%s=%s' % (p_k, p_v))140141 collector.append(value)142 collector.append('; ')143144 if len(params):145146 collector.append('; '.join(_params))147148 if not len(headers) == i+1:149 collector.append(', ')150151152 # Remove trailing separators.153 if collector[-1] in (', ', '; '):154 del collector[-1]155156 return ''.join(collector)157158159160def 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)173174175def dict_from_cookiejar(cj):176 """Returns a key/value dictionary from a CookieJar.177178 :param cj: CookieJar object to extract cookies from.179 """180181 cookie_dict = {}18220 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.value
1 unmodified line
189 return cookie_dict190191192def cookiejar_from_dict(cookie_dict):30 """Returns a CookieJar from a key/value dictionary."""193 """Returns a CookieJar from a key/value dictionary.194195 :param cookie_dict: Dict of key/values to insert into CookieJar.196 """197198 # return cookiejar if one was passed in199 if isinstance(cookie_dict, cookielib.CookieJar):200 return cookie_dict201
5 unmodified lines
207 return cj208209210def 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.212213 :param cj: CookieJar to insert cookies into.214 :param cookie_dict: Dict of key/values to insert into CookieJar.215 """216217 for k, v in cookie_dict.items():218219 cookie = cookielib.Cookie(220 version=0,
18 unmodified lines
239 # add cookie to cookiejar240 cj.set_cookie(cookie)241242 return cj243244245def get_encodings_from_content(content):246 """Returns encodings from given content string.247248 :param content: bytestring to extract encodings from.249 """250251 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)252253 return charset_re.findall(content)254255256def get_encoding_from_headers(headers):257 """Returns encodings from given HTTP Header Dict.258259 :param headers: dictionary to extract encoding from.260 """261262 content_type = headers.get('content-type')263264 if not content_type:265 return None266267 content_type, params = cgi.parse_header(content_type)268269 if 'charset' in params:270 return params['charset'].strip("'\"")271272273def unicode_from_html(content):274 """Attempts to decode an HTML string into unicode.275 If unsuccessful, the original content is returned.276 """277278 encodings = get_encodings_from_content(content)279280 for encoding in encodings:281282 try:283 return unicode(content, encoding)284 except (UnicodeError, TypeError):285 pass286287 return content288289290def 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 return297298 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 rv306307308def get_unicode_from_response(r):309 """Returns the requested content back in unicode.310311 :param r: Response object to get unicode content from.312313 Tried:314315 1. charset from content-type316317 2. every encodings from ``<meta ... charset=XXX>``318319 3. fall back and replace all unicode characters320321 """322323 tried_encodings = []324325 # Try charset from content-type326 encoding = get_encoding_from_headers(r.headers)327328 if encoding:329 try:330 return unicode(r.content, encoding)331 except UnicodeError:332 tried_encodings.append(encoding)333334 # Fall back:335 try:336 return unicode(r.content, encoding, errors='replace')337 except TypeError:338 return r.content339340341def decode_gzip(content):342 """Return gzip-decoded string.343344 :param content: bytestring to gzip-decode.345 """346347 return zlib.decompress(content, 16 + zlib.MAX_WBITS)348349350def 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 pass
modified:.gitignore+1 added
5 unmodified lines
6*.pyc7docs/_build8toy.py9.gitignore10junit-report.xml
modified:AUTHORS+7 added
38 unmodified lines
39- 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 Hengeveld
deleted:AUTHORS.orig-40 removed
1Requests is written and maintained by Kenneth Reitz and2various contributors:34Development Lead5````````````````67- Kenneth Reitz <me@kennethreitz.com>8910Patches and Suggestions11```````````````````````1213- 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>>>>>>> 0ed641a26ec2200de00e4bbf3d170c767375351e
deleted:HACKING-15 removed
1Where possible, please follow PEP8 with regard to coding style. Sometimes the2line length restriction is too hard to follow, so don't bend over backwards3there.45Triple-quotes should always be """, single quotes are ' unless using " would6result in less escaping within the string.78All modules, functions, and methods should be well documented reStructuredText9for Sphinx AutoDoc.1011All functionality should be available in pure Python. Optional C (via Cython)12implementations may be written for performance reasons, but should never13replace the Python implementation.1415Lastly, don't take yourself too seriously :)
modified:HISTORY.rst+58 added
1History2-------340.7.2 (2011-10-23)5++++++++++++++++++67* PATCH Fix.89100.7.1 (2011-10-23)11++++++++++++++++++1213* Move away from urllib2 authentication handling.14* Fully Remove AuthManager, AuthObject, &c.15* New tuple-based auth system with handler callbacks.1617180.7.0 (2011-10-22)19++++++++++++++++++2021* Sessions are now the primary interface.22* Deprecated InvalidMethodException.23* PATCH fix.24* New config system (no more global settings).2526270.6.6 (2011-10-19)28++++++++++++++++++2930* Session parameter bugfix (params merging).3132330.6.5 (2011-10-18)34++++++++++++++++++3536* Offline (fast) test suite.37* Session dictionary argument merging.3839400.6.4 (2011-10-13)41++++++++++++++++++4243* 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.4849500.6.3 (2011-10-13)51++++++++++++++++++5253* Beautiful ``requests.async`` module, for making async requests w/ gevent.5455560.6.2 (2011-10-09)57++++++++++++++++++5859* GET/HEAD obeys allow_redirects=False.6061620.6.1 (2011-08-20)63++++++++++++++++++6465* Enhanced status codes experience ``\o/``
18 unmodified lines
84* HTTPError handling improvements85* Improved https testing86* Bugfixes8788890.5.1 (2011-07-23)90++++++++++++++++++9192* International Domain Name Support!
127 unmodified lines
added:Makefile+16 added
1init:2 pip install -r reqs.txt34test:5 nosetests test_requests.py67ci: init8 nosetests test_requests.py --with-xunit --xunit-file=junit-report.xml910stats:11 pyflakes requests | awk -F\: '{printf "%s:%s: [E]%s\n", $1, $2, $3}' > violations.pyflakes.txt1213site:14 cd docs; make dirhtml1516docs: site
modified:MANIFEST.in+1 added-1 removed
1include README.rst LICENSE HISTORY.rst 1include README.rst LICENSE HISTORY.rst test_requests.py
modified:README.rst+9 added-13 removed
32 unmodified lines
3334Features35--------3637- 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.4648- Simple Authentication49 + Simple URL + HTTP Auth Registry475148Usage49-----5051It couldn't be simpler. ::
49 unmodified lines
added:reqs.txt+7 added
1envoy==0.0.22httpbin==0.0.43gunicorn4nose5pyflakes6omnijson7rudolf
modified:test_requests.py+112 added-72 removed
1 unmodified line
2# -*- coding: utf-8 -*-34from __future__ import with_statement56import unittest6import time7import cookielib8import os9import unittest1011import requests12import envoy1314try:15 import omnijson as json16except ImportError:17 import json1814import requests1916from requests.sessions import Session20# TODO: Detect an open port.21PORT = os.environ.get('HTTPBIN_PORT', '7077')2223HTTPBIN_URL = 'http://0.0.0.0:%s/' % (PORT)24# HTTPBIN_URL = 'http://127.0.0.1:8000/'2519HTTPBIN_URL = 'http://httpbin.org/'20HTTPSBIN_URL = 'https://httpbin.ep.io/'2622# HTTPBIN_URL = 'http://staging.httpbin.org/'23# HTTPSBIN_URL = 'https://httpbin-staging.ep.io/'242527def httpbin(*suffix):28 """Returns url for HTTPBIN resource."""2930 return HTTPBIN_URL + '/'.join(suffix)313232def httpsbin(*suffix):33 """Returns url for HTTPSBIN resource."""33SERVICES = (httpbin, )3435 return HTTPSBIN_URL + '/'.join(suffix)35_httpbin = False3637class RequestsTestSuite(unittest.TestCase):38 """Requests test cases."""3938SERVICES = (httpbin, httpsbin)40 # It goes to eleven.41 _multiprocess_can_split_ = True4243 def setUp(self):4445 global _httpbin4642class RequestsTestSuite(unittest.TestCase):43 """Requests test cases."""47 if not _httpbin:4849 c = envoy.connect('gunicorn httpbin:app --bind=0.0.0.0:%s' % (PORT))5046 def setUp(self):47 pass51 self.httpbin = c52 _httpbin = True53 time.sleep(1)54555657 def tearDown(self):58 """Teardown."""52 pass59 # self.httpbin.kill()6061 def test_entry_points(self):62 import requests6364 requests.session65 requests.session().get66 requests.session().head67 requests.get68 requests.head69 requests.put70 requests.patch71 requests.post72737475 def test_invalid_url(self):76 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')775878 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)816364 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)8586 def test_HTTP_302_GET(self):87 r = requests.get(httpbin('redirect', '1'), allow_redirects=False)88 self.assertEqual(r.status_code, 302)899091 def test_HTTP_200_OK_GET_WITH_PARAMS(self):92 heads = {'User-agent': 'Mozilla/5.0'}9394 r = requests.get(httpbin('user-agent'), headers=heads)
29 unmodified lines
124 self.assertTrue(heads['user-agent'] in r.content)125126127 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)130131110 def test_HTTPS_200_OK_HEAD(self):111 r = requests.head(httpsbin('/'))112 self.assertEqual(r.status_code, 200)113114132 def test_HTTP_200_OK_PUT(self):133 r = requests.put(httpbin('put'))134 self.assertEqual(r.status_code, 200)135136120 def test_HTTPS_200_OK_PUT(self):121 r = requests.put(httpsbin('put'))122 self.assertEqual(r.status_code, 200)123124137 def test_HTTP_200_OK_PATCH(self):138 r = requests.patch(httpbin('patch'))139 self.assertEqual(r.status_code, 200)140141130 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):143134135 def test_AUTH_HTTP_200_OK_GET(self):136144 for service in SERVICES:145146 auth = ('user', 'pass')147 url = service('basic-auth', 'user', 'pass')148149 r = requests.get(url, auth=auth)143 # print r.__dict__150 self.assertEqual(r.status_code, 200)151146152 r = requests.get(url)153 self.assertEqual(r.status_code, 401)154155156 s = requests.session(auth=auth)157 r = s.get(url)158 self.assertEqual(r.status_code, 200)159160161 def test_DIGESTAUTH_HTTP_200_OK_GET(self):162163 for service in SERVICES:164165 auth = ('digest', 'user', 'pass')166 url = service('digest-auth', 'auth', 'user', 'pass')167168 r = requests.get(url, auth=auth)169 self.assertEqual(r.status_code, 200)170171 r = requests.get(url)172 self.assertEqual(r.status_code, 401)173174175 s = requests.session(auth=auth)176 r = s.get(url)177 self.assertEqual(r.status_code, 200)178179 def test_POSTBIN_GET_POST_FILES(self):180181 for service in SERVICES:182
41 unmodified lines
224225 r = requests.get(service('status', '500'))226 self.assertEqual(bool(r), False)227200 r = requests.get(service('/'))228 r = requests.get(service('/get'))229 self.assertEqual(bool(r), True)230231232 def test_request_ok_set(self):
42 unmodified lines
275 def test_unicode_get(self):276277 for service in SERVICES:278251 url = service('/')279 url = service('/get')280281 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 lines
293 r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)294 self.assertEquals(r.status_code, 401)295296269 def test_settings(self):270271 def test():272 r = requests.get(httpbin(''))273 r.raise_for_status()274275 with requests.settings(timeout=0.0000001):276 self.assertRaises(requests.Timeout, test)277278 with requests.settings(timeout=100):279 requests.get(httpbin(''))280281297 def test_urlencoded_post_data(self):298299 for service in SERVICES:300
90 unmodified lines
391 self.assertEquals(rbody.get('form'), None)392 self.assertEquals(rbody.get('data'), 'foobar')393394380 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.url398399400 def test_urlencoded_get_query_multivalued_param(self):401
72 unmodified lines
474475476 def test_session_HTTP_200_OK_GET(self):477463 s = Session()464 r = s.get(httpbin('/'))478 s = requests.session()479 r = s.get(httpbin('/get'))480 self.assertEqual(r.status_code, 200)481482468 def test_session_HTTPS_200_OK_GET(self):469470 s = Session()471 r = s.get(httpsbin('/'))472 self.assertEqual(r.status_code, 200)473474483 def test_session_persistent_headers(self):484485 heads = {'User-agent': 'Mozilla/5.0'}486479 s = Session()487 s = requests.session()488 s.headers = heads489490 # Make 2 requests from Session object, should send header both times491 r1 = s.get(httpbin('user-agent'))483492 assert heads['User-agent'] in r1.content485 r2 = s.get(httpbin('user-agent'))493494 r2 = s.get(httpbin('user-agent'))495 assert heads['User-agent'] in r2.content496497 new_heads = {'User-agent': 'blah'}498 r3 = s.get(httpbin('user-agent'), headers=new_heads)499 assert new_heads['User-agent'] in r3.content500501 self.assertEqual(r2.status_code, 200)502503504 def test_session_persistent_params(self):505506 params = {'a': 'a_test'}507508 s = requests.session()509 s.params = params510511 # Make 2 requests from Session object, should send header both times512 r1 = s.get(httpbin('get'))513 assert params['a'] in r1.content514515516 params2 = {'b': 'b_test'}517518 r2 = s.get(httpbin('get'), params=params2)519 assert params['a'] in r2.content520 assert params2['b'] in r2.content521522523 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}524525 r3 = s.get(httpbin('get'), params=params3)526527 assert not params['a'] in r3.content528 assert params3['b'] in r3.content529 assert params3['c'] in r3.content530531532if __name__ == '__main__':533 unittest.main()
deleted:tox.ini-8 removed
1[tox]2envlist = py25,py26,py2734[testenv]5commands=py.test --junitxml=junit-{envname}.xml6deps =7 pytest8 omnijson