Merge branch 'develop'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 95ba6fc, 9471b0a · Browse files · 30 files·+1157 added−340 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
30 files+1157 added−340 removed
- other:+1157 added−340 removed
Provenance
- Commit
81d5997- Tree
75837b1- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
95ba6fc- Parent 2
9471b0a
30 files changed+1157 added−340 removed
added:debian/changelog+5 added
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 -0500added:debian/compat+1 added
1+5added:debian/control+13 added
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.added:debian/docs+1 added
1+docs/user/*.rstadded:debian/pyversions+1 added
1+2.4-added:debian/rules+42 added
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+added:docs/community/faq.rst+43 added
1+.. _faq:2+3+Frequently Asked Questions4+==========================5+6+This part of the documentation covers common questions about Requests.7+8+Why not Httplib2?9+-----------------10+11+Chris Adams gave an excellent summary on12+`Hacker News <http://news.ycombinator.com/item?id=2884406>`_:13+14+ httplib2 is part of why you should use requests: it's far more respectable15+ as a client but not as well documented and it still takes way too much code16+ for basic operations. I appreciate what httplib2 is trying to do, that17+ there's a ton of hard low-level annoyances in building a modern HTTP18+ client, but really, just use requests instead. Kenneth Reitz is very19+ motivated and he gets the degree to which simple things should be simple20+ whereas httplib2 feels more like an academic exercise than something21+ people should use to build production systems[1].22+23+ Disclosure: I'm listed in the requests AUTHORS file but can claim credit24+ for, oh, about 0.0001% of the awesomeness.25+26+ 1. http://code.google.com/p/httplib2/issues/detail?id=96 is a good example:27+ an annoying bug which affect many people, there was a fix available for28+ months, which worked great when I applied it in a fork and pounded a couple29+ TB of data through it, but it took over a year to make it into trunk and30+ even longer to make it onto PyPI where any other project which required "31+ httplib2" would get the working version.32+33+34+Python 3 Support?35+-----------------36+37+It's on the way. Here's a list of `supported interpreters <interpreters>`_.38+39+40+Keep-alive Support?41+-------------------42+43+It's on the way.added:docs/community/support.rst+37 added
1+.. _support:2+3+Support4+=======5+6+If you have a questions or issues about Requests, there are serveral options:7+8+Send a Tweet9+------------10+11+If your question is less than 140 characters, feel free to send a tweet to12+`@kennethreitz <http://twitter.com/kennethreitz>`_.13+14+15+File an Issue16+-------------17+18+If you notice some unexpected behavior in Requests, or want to see support19+for a new feature,20+`file an issue on GitHub <https://github.com/kennethreitz/requests/issues>`_.21+22+23+E-mail24+------25+26+I'm more than happy to answer any personal or in-depth questions about27+Requests. Feel free to email28+`requests@kennethreitz.com <mailto:requests@kennethreitz.com>`_.29+30+31+IRC32+---33+34+The official Freenode channel for Requests is35+`#python-requests <irc://irc.freenode.net/python-requests>`_36+37+I'm also available as **kennethreitz** on Freenode.added:docs/community/updates.rst+31 added
1+.. _updates:2+3+Updates4+=======5+6+If you'd like to stay up to date on the community and development of Requests,7+there are serveral options:8+9+GitHub10+------11+12+The best way to track the development of Requests is through13+`the GitHub repo <https://github.com/kennethreitz/requests>`_.14+15+Twitter16+-------17+18+I often tweet about new features and releases of Requests.19+20+Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.21+22+23+24+Mailing List25+------------26+27+There's a low-volume mailing list for Requests. To subscribe to the28+mailing list, send an email to29+`requests@librelist.org <mailto:requests@librelist.org>`_.30+31+added:docs/dev/authors.rst+5 added
1+Authors2+=======3+4+5+.. include:: ../../AUTHORSmodified:docs/user/advanced.rst+137 added
1+.. _advanced:2+3+Advanced Usage4+==============5+6+This document covers some of Requests more advanced features.7+8+9+Session Objects10+---------------11+12+The Session object allows you to persist certain parameters across13+requests. It also establishes a CookieJar and passes it along14+to any requests made from the Session instance.15+16+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:21+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"}}'27+28+29+Sessions can also be used to provide default data to the request methods::30+31+ headers = {'x-test': 'true'}32+ auth = ('user', 'pass')33+34+ with requests.session(auth=auth, headers=headers) as c:35+36+ # both 'x-test' and 'x-test2' are sent37+ c.get('http://httpbin.org/headers', header={'x-test2', 'true'})38+39+40+.. admonition:: Global Settings41+42+ Certain parameters are best set at the ``request.config`` level43+ (e.g.. a global proxy, user agent header).44+45+46+Event Hooks47+-----------48+49+Requests has a hook system that you can use to manipulate portions of50+the request process, or signal event handling.51+52+Available hooks:53+54+``args``:55+ A dictionary of the arguments being sent to Request().56+57+``pre_request``:58+ The Request object, directly before being sent.59+60+``post_request``:61+ The Request object, directly after being sent.62+63+``response``:64+ The response generated from a Request.65+66+67+You can assign a hook function on a per-request basis by passing a68+``{hook_name: callback_function}`` dictionary to the ``hooks`` request69+paramaeter::70+71+ hooks=dict(args=print_url)72+73+That ``callback_function`` will receive a chunk of data as its first74+argument.75+76+::77+78+ def print_url(args):79+ print args['url']80+81+If an error occurs while executing your callback, a warning is given.82+83+If the callback function returns a value, it is assumed that it is to84+replace the data that was passed in. If the function doesn't return85+anything, nothing else is effected.86+87+Let's print some request method arguments at runtime::88+89+ >>> requests.get('http://httpbin', hooks=dict(args=print_url))90+ http://httpbin91+ <Response [200]>92+93+Let's hijack some arguments this time with a new callback::94+95+ def hack_headers(args):96+ if not args[headers]:97+ args['headers'] = dict()98+99+ args['headers'].update({'X-Testing': 'True'})100+101+ return args102+103+ hooks = dict(args=hack_headers)104+ headers = dict(yo=dawg)105+106+And give it a try::107+108+ >>> requests.get('http://httpbin/headers', hooks=hooks, headers=headers)109+ {110+ "headers": {111+ "Content-Length": "",112+ "Accept-Encoding": "gzip",113+ "Yo": "dawg",114+ "X-Forwarded-For": "::ffff:24.127.96.129",115+ "Connection": "close",116+ "User-Agent": "python-requests.org",117+ "Host": "httpbin.org",118+ "X-Testing": "True",119+ "X-Forwarded-Protocol": "",120+ "Content-Type": ""121+ }122+ }123+124+125+126+Verbose Logging127+---------------128+129+If you want to get a good look at what HTTP requests are being sent130+by your application, you can turn on verbose logging.131+132+To do so, just configure Requests with a stream to write to::133+134+ >>> requests.settings.verbose = sys.stderr135+ >>> requests.get('http://httpbin.org/headers')136+ 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers137+ <Response [200]>modified:docs/user/install.rst+3 added-3 removed
13 unmodified lines14 $ pip install requests15 16 or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::17 18- $ easy_install install requests18+ $ easy_install requests19 20 But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21 22 23 24 Cheeseshop Mirror25 -----------------26 27-If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <pip.kreitz.co/>`_::27+If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::28 29 $ pip install -i http://pip.kreitz.co/simple requests30 31 32 Get the Code33 ------------34 35-Requsts is actively developed on GitHub, where the code is35+Requests is actively developed on GitHub, where the code is36 `always available <https://github.com/kennethreitz/requests>`_.37 38 You can either clone the public repository::39 14 unmodified linesmodified:docs/user/intro.rst+9 added
1+.. _introduction:2+3 Introduction4 ============5 6 Philosophy34 unmodified lines41 42 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.43 44 45+.. _interpreters:46 Python Interpreters47 -------------------48 49 At this time, the following Python platforms are officially supported:50 51 * cPython 2.552+* cPython 2.5.553+* cPython 2.5.654 * cPython 2.655+* cPython 2.6.656+* cPython 2.6.757 * cPython 2.758+* cPython 2.7.159+* cPython 2.7.260 * PyPy-c 1.461 * PyPy-c 1.562 63 1 unmodified linemodified:docs/user/quickstart.rst+98 added-48 removed
1-Feature Overview2-================1+.. _quickstart:2 4-Requests is designed to solve a 90% use case — making simple requests. While most5-HTTP libraries are extremely extensible, they often attempt to support the entire HTTP Spec.6-This often leads to extremely messy and cumbersome APIs, as is the case with urllib2. Requests abandons support for edge-cases, and focuses on the essentials.3+Quickstart4+==========5 6+.. module:: requests.models7 9-.. _features:8+Eager to get started? This page gives a good introduction in how to get started with Requests. This assumes you already have Requests installed. If you do not, head over to the :ref:`Installation <install>` section.9 11-Requests Can:12--------------10+First, make sure that:11 14-- Make **GET**, **POST**, **PUT**, **DELETE**, and **HEAD** requests.15-- Handle HTTP and HTTPS Requests16-- Add Request headers (with a simple dictionary)17-- URLEncode your Form Data (with a simple dictionary)18-- Add Multi-part File Uploads (with a simple dictionary)19-- Handle CookieJars (with a single parameter)20-- Add HTTP Authentication (with a single parameter)21-- Handle redirects (with history)22-- Automatically decompress GZip'd responses23-- Support Unicode URLs24-- Gracefully timeout25-- Interface with Eventlet & Gevent12+* Requests is :ref:`installed <install>`13+* Requests is :ref:`up-to-date <updates>`14 15 28-Requests Can't:29----------------16+Lets gets started with some simple use cases and examples.17 31-- Handle Caching32-- Handle Keep-Alives18 19+Make a GET Request20+------------------21 35-Quickstart36-==========22+Making a standard request with Requests is very simple.23 24+Let's get GitHub's public timeline ::25 39-GET Request40------------26+ r = requests.get('https://github.com/timeline.json')27 28+Now, we have a :class:`Response` object called ``r``. We can get all the information we need from this.29 43-Adding Parameters44------------------30 31+Response Content32+----------------33 34+We can read the content of the server's response::35 48-Adding Headers49---------------36+ >>> r.content37+ '[{"repository":{"open_issues":0,"url":"https://github.com/...38 39 40+Response Status Codes41+---------------------42 53-HTTP Basic Auth54----------------43+We can check the response status code::44 45+ >>> r.status_code46+ 20047 57-Tracking Redirects58-------------------48+Requests also comes with a built-in status code lookup object for easy49+reference::50 51+ >>> r.status_code == requests.codes.ok52+ True53 54+If we made a bad request, we can raise it with55+:class:`Response.raise_for_status()`::56 57+ >>> _r = requests.get('http://httpbin.org/status/404')58+ >>> _r.status_code59+ 40460 63-HTTP POST (Form Data)64----------------------61+ >>> _r.raise_for_status()62+ Traceback (most recent call last):63+ File "requests/models.py", line 394, in raise_for_status64+ raise self.error65+ urllib2.HTTPError: HTTP Error 404: NOT FOUND66 67+But, since our ``status_code`` was ``200``, when we call it::68 67-HTTP POST (Binary Data)68------------------------69+ >>> r.raise_for_status()70+ None71 72+All is well.73 71-HTTP POST (Multipart Files)72----------------------------74 75+Response Headers76+----------------77 75-HTTP PUT76---------78+We can view the server's response headers with a simple Python dictionary79+interface::80 81+ >>> r.headers82+ {83+ 'status': '200 OK',84+ 'content-encoding': 'gzip',85+ 'transfer-encoding': 'chunked',86+ 'connection': 'close',87+ 'server': 'nginx/1.0.4',88+ 'x-runtime': '148ms',89+ 'etag': '"e1ca502697e5c9317743dc078f67693f"',90+ 'content-type': 'application/json; charset=utf-8'91+ }92 79-HTTP DELETE80------------93+The dictionary is special, though: it's made just for HTTP headers. According to `RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP94+Headers are case-insensitive.95 96+So, we can access the headers using any capitalization we want::97 83-HTTP HEAD84----------98+ >>> r.headers['Content-Type']99+ 'application/json; charset=utf-8'100+101+ >>> r.headers.get('content-type')102+ 'application/json; charset=utf-8'103+104+If a header doesn't exist in the Response, its value defaults to ``None``::105+106+ >>> r.headers['X-Random']107+ None108+109+110+Cookies111+-------112+113+If a response contains some Cookies, you can get quick access to them::114+115+ >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'116+ >>> r = requests.get(url)117+118+ >>> print r.cookies119+ {'requests-is': 'awesome'}120+121+The underlying CookieJar is also available for more advanced handing::122+123+ >>> r.request.cookiejar124+ <cookielib.CookieJar>125+126+To send your own cookies to the server, you can use the ``cookies``127+parameter::128+129+ >>> url = 'http://httpbin.org/cookies'130+ >>> cookies = dict(cookies_are='working')131+132+ >>> r = requests.get(url, cookies=cookies)133+ >>> r.content134+ '{"cookies": {"cookies_are": "working"}}'modified:docs/api.rst+1 added-12 removed
20 unmodified lines21 .. autofunction:: post22 .. autofunction:: put23 .. autofunction:: patch24 .. autofunction:: delete25+.. autofunction:: request26 26-27 -----------28 29 30 .. autoclass:: requests.models.Response18 unmodified lines49 These items are an internal component to Requests, and should never be50 seen by the end user (developer). This part of the API documentation51 exists for those who are extending the functionality of Requests.52 53-Functions54-~~~~~~~~~55-56-.. autofunction:: request57-53 Classes54 ~~~~~~~55 56 .. autoclass:: requests.models.Request57 :inherited-members:63-64-Structures65-~~~~~~~~~~66-67-.. autoclass:: requests.structures.CaseInsensitiveDict68- :inherited-members:modified:docs/conf.py+1 added-1 removed
153 unmodified lines154 # If true, the index is split into individual pages for each letter.155 #html_split_index = False156 157 # If true, links to the reST sources are added to the pages.158-html_show_sourcelink = True158+html_show_sourcelink = False159 160 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.161 html_show_sphinx = False162 82 unmodified linesmodified:docs/index.rst+29 added-7 removed
11 unmodified lines12 13 Most existing Python modules for sending HTTP requests are extremely verbose14 and cumbersome. Python's builtin **urllib2** module provides most of15 the HTTP capabilities you should need, but the api is thoroughly **broken**.16-It requires an *enormous* amount of work (even method overrides) to perform the simplest of tasks.16+It requires an *enormous* amount of work (even method overrides) to perform17+the simplest of tasks.18 19 Things shouldn’t be this way. Not in Python.20 21 ::22 23 >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))24 >>> r.status_code24- 20025+ 20426 >>> r.headers['content-type']27 'application/json'28+ >>> r.content29+ ...30 31 See `the same code, without Requests <https://gist.github.com/973705>`_.32 33 Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,7 unmodified lines41 42 `Twitter, Inc <http://twitter.com>`_ uses Requests internally.43 44 **Daniel Greenfeld**42- Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to @kennethreitz's request library. Today has been AWESOME.45+ Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to46+ @kennethreitz's request library. Today has been AWESOME.47 48 **Kenny Meyers**45- Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful, simple, Pythonic.49+ Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,50+ simple, Pythonic.51 52 **Rich Leland**53 Requests is awesome. That is all.54 55 **Steve Pike**51- I can never remember how to do it the regular way. ``import requests; requests.get()`` is just so easy!56+ I can never remember how to do it the regular way.57+ ``import requests; requests.get()`` is just so easy!58 59 60 User Guide61 ----------62 57-This part of the documentation, which is mostly prose, begins with some background information about Requests, then focuses on step-by-step instructions for getting the most out of Requests.63+This part of the documentation, which is mostly prose, begins with some64+background information about Requests, then focuses on step-by-step65+instructions for getting the most out of Requests.66 67 .. toctree::68 :maxdepth: 269 70 user/intro71 user/install64-.. user/quickstart72+ user/quickstart73 user/advanced74 75 76+Community Guide77+-----------------78+79+This part of the documentation, which is mostly prose, details the80+Requests ecosystem and community.81+82+.. toctree::83+ :maxdepth: 284+85+ community/faq86+ community/support87+ community/updates88+89 API Documentation90 -----------------91 92 If you are looking for information on a specific function, class or method,15 unmodified lines108 :maxdepth: 2109 110 dev/internals111 dev/todo112+ dev/authorsmodified:requests/api.py+50 added-50 removed
10 unmodified lines11 12 """13 14 import config15-from .models import Request, Response, AuthManager, AuthObject, auth_manager15+from .models import Request, Response, AuthObject16+from .status_codes import codes17+from .hooks import dispatch_hook18+from .utils import cookiejar_from_dict19 20+from urlparse import urlparse21 22 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')23 24 def request(method, url,25 params=None, data=None, headers=None, cookies=None, files=None, auth=None,22- timeout=None, allow_redirects=False, proxies=None):26+ timeout=None, allow_redirects=False, proxies=None, hooks=None):27 24- """Constructs and sends a :class:`Request <models.Request>`. Returns :class:`Response <models.Response>` object.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`.31- :param cookies: (optional) CookieJar object 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 39- r = Request(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,47- auth = auth or auth_manager.get_auth(url),57+ auth = auth,58 timeout = timeout or config.settings.timeout,59 allow_redirects = allow_redirects,50- proxies = proxies60+ proxies = proxies or config.settings.proxies,61 )62 63+ # Arguments manipulation hook.64+ args = dispatch_hook('args', hooks, args)65+66+ r = Request(**args)67+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 58-def get(url,59- params=None, headers=None, cookies=None, auth=None, timeout=None,60- proxies=None):83+def get(url, **kwargs):84 85 """Sends a GET request. Returns :class:`Response` object.86 87 :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`.67- :param cookies: (optional) CookieJar object 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 proxies: (optional) Dictionary mapping protocol to the URL of the proxy.94 """95 73- return request('GET', url,74- params=params, headers=headers, cookies=cookies, auth=auth,75- timeout=timeout, proxies=proxies)96+ return request('GET', url, **kwargs)97 98 78-def head(url,79- params=None, headers=None, cookies=None, auth=None, timeout=None,80- proxies=None):99+def head(url, **kwargs):100 101 """Sends a HEAD request. Returns :class:`Response` object.102 103 :param url: URL for the new :class:`Request` object.104 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.105 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.87- :param cookies: (optional) CookieJar object to send with the :class:`Request`.106+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.107 :param auth: (optional) AuthObject to enable Basic HTTP Auth.108 :param timeout: (optional) Float describing the timeout of the request.109 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.110 """111 93- return request('HEAD', url,94- params=params, headers=headers, cookies=cookies, auth=auth,95- timeout=timeout, proxies=proxies)112+ return request('HEAD', url, **kwargs)113 114 98-def post(url,99- data='', headers=None, files=None, cookies=None, auth=None, timeout=None,100- allow_redirects=False, params=None, proxies=None):115+def post(url, data='', **kwargs):116 117 """Sends a POST request. Returns :class:`Response` object.118 119 :param url: URL for the new :class:`Request` object.120 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.121 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.122 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.108- :param cookies: (optional) CookieJar object to send with the :class:`Request`.123+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.124 :param auth: (optional) AuthObject to enable Basic HTTP Auth.125 :param timeout: (optional) Float describing the timeout of the request.126 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.127 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.128 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.129 """130 116- return request('POST', url,117- params=params, data=data, headers=headers, files=files,118- cookies=cookies, auth=auth, timeout=timeout,119- allow_redirects=allow_redirects, proxies=proxies)131+ return request('POST', url, data=data, **kwargs)132 133 122-def put(url, data='', headers=None, files=None, cookies=None, auth=None,123- timeout=None, allow_redirects=False, params=None, proxies=None):134+def put(url, data='', **kwargs):135 """Sends a PUT request. Returns :class:`Response` object.136 137 :param url: URL for the new :class:`Request` object.138 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.139 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.140 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.130- :param cookies: (optional) CookieJar object to send with the :class:`Request`.141+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.142 :param auth: (optional) AuthObject to enable Basic HTTP Auth.143 :param timeout: (optional) Float describing the timeout of the request.144 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.145 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.146 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.147 """148 138- return request('PUT', url,139- params=params, data=data, headers=headers, files=files,140- cookies=cookies, auth=auth, timeout=timeout,141- allow_redirects=allow_redirects, proxies=proxies)149+ return request('PUT', url, data=data, **kwargs)150 151 144-def patch(url, data='', headers=None, files=None, cookies=None, auth=None,145- timeout=None, allow_redirects=False, params=None, proxies=None):152+def patch(url, data='', **kwargs):153 """Sends a PATCH request. Returns :class:`Response` object.154 155 :param url: URL for the new :class:`Request` object.156 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.157 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.158 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.152- :param cookies: (optional) CookieJar object to send with the :class:`Request`.159+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.160 :param auth: (optional) AuthObject to enable Basic HTTP Auth.161 :param timeout: (optional) Float describing the timeout of the request.162 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.163 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.164 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.165 """166 160- return request('PATCH', url,161- params=params, data=data, headers=headers, files=files,162- cookies=cookies, auth=auth, timeout=timeout,163- allow_redirects=allow_redirects, proxies=proxies)167+ return request('PATCH', url, **kwargs)168 169 166-def delete(url,167- params=None, headers=None, cookies=None, auth=None, timeout=None,168- allow_redirects=False, proxies=None):170+def delete(url, **kwargs):171 172 """Sends a DELETE request. Returns :class:`Response` object.173 174 :param url: URL for the new :class:`Request` object.175 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.176 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.175- :param cookies: (optional) CookieJar object to send with the :class:`Request`.177+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.178 :param auth: (optional) AuthObject to enable Basic HTTP Auth.179 :param timeout: (optional) Float describing the timeout of the request.180 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.181 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.182 """183 182- return request('DELETE', url,183- params=params, headers=headers, cookies=cookies, auth=auth,184- timeout=timeout, allow_redirects=allow_redirects, proxies=proxies)184+ return request('DELETE', url, **kwargs)modified:requests/config.py+10 added-2 removed
10 unmodified lines11 class Settings(object):12 _singleton = {}13 14 # attributes with defaults15- __attrs__ = ('timeout', 'verbose')15+ __attrs__ = []16 17 def __init__(self, **kwargs):18 super(Settings, self).__init__()19 32 unmodified lines52 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'}58-settings.accept_gzip = True60+settings.accept_gzip = True61+settings.proxies = None62+settings.verbose = None63+settings.timeout = None64+65+#: Use socket.setdefaulttimeout() as fallback?66+settings.timeout_fallback = Truemodified:requests/core.py+5 added-3 removed
10 unmodified lines11 12 """13 14 __title__ = 'requests'15-__version__ = '0.5.1'16-__build__ = 0x00050115+__version__ = '0.6.0'16+__build__ = 0x00060017 __author__ = 'Kenneth Reitz'18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 21 22-from models import HTTPError, auth_manager22+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/hooks.py+40 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.hooks5+~~~~~~~~~~~~~~6+7+This module provides the capabilities for the Requests hooks system.8+9+Available hooks:10+11+``args``:12+ A dictionary of the arguments being sent to Request().13+14+``pre_request``:15+ The Request object, directly before being sent.16+17+``post_request``:18+ The Request object, directly after being sent.19+20+``response``:21+ The response generated from a Request.22+23+"""24+25+import warnings26+27+28+def dispatch_hook(key, hooks, hook_data):29+ """Dipatches a hook dictionary on a given peice of data."""30+31+ hooks = hooks or dict()32+33+ if key in hooks:34+ try:35+ return hooks.get(key).__call__(hook_data) or hook_data36+37+ except Exception, why:38+ warnings.warn(str(why))39+40+ return hook_datamodified:requests/models.py+62 added-18 removed
10 unmodified lines11 import socket12 import zlib13 14 from urllib2 import HTTPError15-from urlparse import urlparse, urlunparse15+from urlparse import urlparse, urlunparse, urljoin16 from datetime import datetime17 18 from .config import settings19 from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20 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, InvalidMethod25 26 27 REDIRECT_STATI = (301, 302, 303, 307)10 unmodified lines38 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 41- socket.setdefaulttimeout(timeout)42+ #: Float describ the timeout of the request.43+ # (Use socket.setdefaulttimeout() as fallback)44+ self.timeout = timeout45 46 #: Request URL.47 self.url = url48+49 #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.50 self.headers = headers51+52 #: Dictionary of files to multipart upload (``{filename: content}``).53 self.files = files54+55 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.56 self.method = method57+58 #: Dictionary or byte of request body data to attach to the59 #: :class:`Request <models.Request>`.60 self.data = None61+62 #: Dictionary or byte of querystring data to attach to the63 #: :class:`Request <models.Request>`.64 self.params = None65+66 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history67 #: and HTTPError storage).68 self.redirect = redirect69+70 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)71 self.allow_redirects = allow_redirects72+73 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})74 self.proxies = proxies75 76 self.data, self._enc_data = self._encode_params(data)6 unmodified lines83 if isinstance(auth, (list, tuple)):84 auth = AuthObject(*auth)85 if not auth:86 auth = auth_manager.get_auth(self.url)87+88 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89 self.auth = auth90+91 #: CookieJar to attach to :class:`Request <models.Request>`.92 self.cookiejar = cookiejar93+94 #: True if Request has been sent.95 self.sent = False96 97 42 unmodified lines140 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))141 142 if self.auth:143 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):144+ # TODO: REMOVE THIS COMPLETELY145 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)146 self.auth.handler = self.auth.handler(auth_manager)147 auth_manager.add_auth(self.url, self.auth)148 23 unmodified lines172 173 return opener.open174 175 161- def _build_response(self, resp):176+ def _build_response(self, resp, is_error=False):177 """Build internal :class:`Response <models.Response>` object from given response."""178 179 def build(resp):180 3 unmodified lines184 try:185 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))186 response.read = resp.read187 response.close = resp.close188+189+ if self.cookiejar:190+191+ response.cookies = dict_from_cookiejar(self.cookiejar)192+193+194 except AttributeError:195 pass196 197+ if is_error:198+ response.error = resp199+200 response.url = getattr(resp, 'url', None)201 202 return response203 16 unmodified lines220 url = r.headers['location']221 222 # Facilitate non-RFC2616-compliant 'location' headers223 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')200- if not urlparse(url).netloc:201- parent_url_components = urlparse(self.url)202- url = '%s://%s/%s' % (parent_url_components.scheme, parent_url_components.netloc, url)224+ url = urljoin(r.url, url)225 226 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4227 if r.status_code is 303:228 method = 'GET'10 unmodified lines239 240 r.history = history241 242 self.response = r243+ self.response.request = self244 245 246 @staticmethod247 def _encode_params(data):18 unmodified lines266 return data, data267 268 269 def _build_url(self):247- """Build the actual URL to use"""270+ """Build the actual URL to use."""271 272 # Support for unicode domain names.273 parsed_url = list(urlparse(self.url))274 parsed_url[1] = parsed_url[1].encode('idna')17 unmodified lines292 293 :param anyway: If True, request will be sent, even if it has294 already been sent.295 """296+297 self._checks()298 success = False299 300 # Logging20 unmodified lines321 else:322 req = _Request(url, data=self._enc_data, method=self.method)323 324 if self.headers:301- req.headers.update(self.headers)325+ for k,v in self.headers.iteritems():326+ req.add_header(k, v)327 328 if not self.sent or anyway:329 330 try:331 opener = self._get_opener()307- resp = opener(req)332+ try:333 334+ resp = opener(req, timeout=self.timeout)335+336+ except TypeError, err:337+ # timeout argument is new since Python v2.6338+ if not 'timeout' in str(err):339+ raise340+341+ if settings.timeout_fallback:342+ # fall-back and use global socket timeout (This is not thread-safe!)343+ old_timeout = socket.getdefaulttimeout()344+ socket.setdefaulttimeout(self.timeout)345+346+ resp = opener(req)347+348+ if settings.timeout_fallback:349+ # restore gobal timeout350+ socket.setdefaulttimeout(old_timeout)351+352 if self.cookiejar is not None:353 self.cookiejar.extract_cookies(resp, req)354 355 except (urllib2.HTTPError, urllib2.URLError), why:356 if hasattr(why, 'reason'):357 if isinstance(why.reason, socket.timeout):358 why = Timeout(why)359 317- self._build_response(why)318- if not self.redirect:319- self.response.error = why360+ self._build_response(why, is_error=True)361 362+363 else:364 self._build_response(resp)365 self.response.ok = True366 325- self.response.cached = False326- else:327- self.response.cached = True367 368 self.sent = self.response.ok369 331-370 return self.sent371 372 373 20 unmodified lines394 #: True if no :attr:`error` occured.395 self.ok = False396 #: Resulting :class:`HTTPError` of request, if one occured.397 self.error = None360- #: True, if the response :attr:`content` is cached locally.361- self.cached = False398 #: A list of :class:`Response <models.Response>` objects from399 #: the history of the Request. Any redirect responses will end400 #: up here.401 self.history = []402+ #: The Request that created the Response.403+ self.request = None404+ #: A dictionary of Cookies the server sent back.405+ self.cookies = None406 407 408 def __repr__(self):409 return '<Response [%s]>' % (self.status_code)96 unmodified lines506 507 508 def reduce_uri(self, uri, default_port=True):509 """Accept authority or URI and extract only the authority and path."""510+511 # note HTTP URLs do not have a userinfo component512 parts = urllib2.urlparse.urlsplit(uri)513+514 if parts[1]:515 # URI516 scheme = parts[0]517 authority = parts[1]2 unmodified lines520 # host or host:port521 scheme = None522 authority = uri523 path = '/'524+525 host, port = urllib2.splitport(authority)526+527 if default_port and port is None and scheme is not None:528 dport = {"http": 80,529 "https": 443,530 }.get(scheme)80 unmodified linesadded:requests/sessions.py+84 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.session5+~~~~~~~~~~~~~~~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_cookiejar16+17+18+19+class Session(object):20+ """A Requests session."""21+22+ __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']23+24+25+ def __init__(self, **kwargs):26+27+ # Set up a CookieJar to be used by default28+ self.cookies = cookielib.FileCookieJar()29+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+38+ def __repr__(self):39+ return '<requests-client at 0x%x>' % (id(self))40+41+ def __enter__(self):42+ return self43+44+ def __exit__(self, *args):45+ # print args46+ pass47+48+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.53+ """54+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())62+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+ )69+70+ if kwargs.get('headers', None) and inst_attrs.get('headers', None):71+ kwargs['headers'].update(inst_attrs['headers'])72+73+ return func(*args, **kwargs)74+ return wrapper_func75+76+ # Map and decorate each function available in requests.api77+ map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),78+ api.__all__)79+80+81+def session(**kwargs):82+ """Returns a :class:`Session` for context-managment."""83+84+ return Session(**kwargs)added:requests/status_codes.py+83 added
1+# -*- coding: utf-8 -*-2+3+from .structures import LookupDict4+5+_codes = {6+7+ # Informational.8+ 100: ('continue',),9+ 101: ('switching_protocols',),10+ 102: ('processing',),11+ 103: ('checkpoint',),12+ 122: ('uri_too_long', 'request_uri_too_long'),13+ 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/'),14+ 201: ('created',),15+ 202: ('accepted',),16+ 203: ('non_authoritative_info', 'non_authoritative_information'),17+ 204: ('no_content',),18+ 205: ('reset_content', 'reset'),19+ 206: ('partial_content', 'partial'),20+ 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),21+ 208: ('im_used',),22+23+ # Redirection.24+ 300: ('multiple_choices',),25+ 301: ('moved_permanently', 'moved'),26+ 302: ('found',),27+ 302: ('see_other', 'other'),28+ 304: ('not_modified',),29+ 305: ('use_proxy',),30+ 306: ('switch_proxy',),31+ 307: ('temporary_redirect', 'temporary_moved', 'temporary'),32+ 308: ('resume_incomplete', 'resume'),33+34+ # Client Error.35+ 400: ('bad_request', 'bad'),36+ 401: ('unauthorized',),37+ 402: ('payment_required', 'payment'),38+ 403: ('forbidden',),39+ 404: ('not_found',),40+ 405: ('method_not_allowed', 'not_allowed'),41+ 406: ('not_acceptable',),42+ 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),43+ 408: ('request_timeout', 'timeout'),44+ 409: ('conflict',),45+ 410: ('gone',),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'),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'),57+ 425: ('unordered_collection', 'unordered'),58+ 426: ('upgrade_required', 'upgrade'),59+ 444: ('no_response', 'none'),60+ 449: ('retry_with', 'retry'),61+ 450: ('blocked_by_windows_parental_controls', 'parental_controls'),62+ 499: ('client_closed_request',),63+64+ # Server Error.65+ 500: ('internal_server_error', 'server_error'),66+ 501: ('not_implemented',),67+ 502: ('bad_gateway',),68+ 503: ('service_unavailable', 'unavailable'),69+ 504: ('gateway_timeout',),70+ 505: ('http_version_not_supported', 'http_version'),71+ 506: ('variant_also_negotiates',),72+ 507: ('insufficient_storage',),73+ 509: ('bandwidth_limit_exceeded', 'bandwidth'),74+ 510: ('not_extended',),75+}76+77+codes = LookupDict(name='status_codes')78+79+for (code, titles) in _codes.items():80+ for title in titles:81+ setattr(codes, title, code)82+ if not title.startswith('\\'):83+ setattr(codes, title.upper(), code)modified:requests/structures.py+18 added
43 unmodified lines44 if key in self:45 return self[key]46 else:47 return default48+49+class LookupDict(dict):50+ """Dictionary lookup object."""51+52+ def __init__(self, name=None):53+ self.name = name54+ super(LookupDict, self).__init__()55+56+ def __repr__(self):57+ return '<lookup \'%s\'>' % (self.name)58+59+ def __getitem__(self, key):60+ # We allow fall-through here, so values default to None61+62+ return self.__dict__.get(key, None)63+64+ def get(self, key, default=None):65+ return self.__dict__.get(key, default)added:requests/utils.py+72 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.utils5+~~~~~~~~~~~~~~6+7+This module provides utlity functions that are used within Requests8+that are also useful for external consumption.9+10+"""11+12+import cookielib13+14+15+def dict_from_cookiejar(cookiejar):16+ """Returns a key/value dictionary from a CookieJar."""17+18+ cookie_dict = {}19+20+ for _, cookies in cookiejar._cookies.items():21+ for _, cookies in cookies.items():22+ for cookie in cookies.values():23+ # print cookie24+ cookie_dict[cookie.name] = cookie.value25+26+ return cookie_dict27+28+29+def cookiejar_from_dict(cookie_dict):30+ """Returns a CookieJar from a key/value dictionary."""31+32+ # return cookiejar if one was passed in33+ if isinstance(cookie_dict, cookielib.CookieJar):34+ return cookie_dict35+36+ # create cookiejar37+ cj = cookielib.CookieJar()38+39+ cj = add_dict_to_cookiejar(cj, cookie_dict)40+41+ return cj42+43+44+def add_dict_to_cookiejar(cj, cookie_dict):45+ """Returns a CookieJar from a key/value dictionary."""46+47+ for k, v in cookie_dict.items():48+49+ cookie = cookielib.Cookie(50+ version=0,51+ name=k,52+ value=v,53+ port=None,54+ port_specified=False,55+ domain='',56+ domain_specified=False,57+ domain_initial_dot=False,58+ path='/',59+ path_specified=True,60+ secure=False,61+ expires=None,62+ discard=True,63+ comment=None,64+ comment_url=None,65+ rest={'HttpOnly': None},66+ rfc2109=False67+ )68+69+ # add cookie to cookiejar70+ cj.set_cookie(cookie)71+72+ return cjmodified:AUTHORS+6 added-1 removed
27 unmodified lines28 - Alberto Paro29 - Jérémy Bethmont30 - 潘旭 (Xu Pan)31 - Tamás Gulácsi32-- Rubén Abad32+- Rubén Abad33+- Peter Manser34+- Jeremy Selier35+- Jens Diemer36+- Alex <@alopatin>37+- Tom Hogans <tomhsx@gmail.com>modified:HISTORY.rst+16 added
1 History2 -------3 4+5+0.6.0 (2011-08-17)6+++++++++++++++++++7+8+* New callback hook system9+* New persistient sessions object and context manager10+* Transparent Dict-cookie handling11+* Status code reference object12+* Removed Response.cached13+* Added Response.request14+* All args are kwargs15+* Relative redirect support16+* HTTPError handling improvements17+* Improved https testing18+* Bugfixes19+20 0.5.1 (2011-07-23)21 ++++++++++++++++++22 23 * International Domain Name Support!127 unmodified linesmodified:README.rst+28 added-78 removed
1 Requests: HTTP for Humans2 =========================3 4-Most existing Python modules for dealing HTTP requests are insane. I have to look up *everything* that I want to do. Most of my worst Python experiences are a result of the various built-in HTTP libraries (yes, even worse than Logging).4+Requests is an ISC Licensed HTTP library, written in Python, for human5+beings.6 6-But this one's different. This one's going to be awesome. And simple.7+Most existing Python modules for sending HTTP requests are extremely8+verbose and cumbersome. Python's builtin urllib2 module provides most of9+the HTTP capabilities you should need, but the api is thoroughly broken.10+It requires an enormous amount of work (even method overrides) to11+perform the simplest of tasks.12 8-Really simple.13+Things shouldn't be this way. Not in Python.14 15+::16+17+ >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))18+ >>> r.status_code19+ 20420+ >>> r.headers['content-type']21+ 'application/json'22+ >>> r.content23+ ...24+25+See `the same code, without Requests <https://gist.github.com/973705>`_.26+27+Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,28+**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,29+multipart files, and parameters with simple Python dictionaries, and access the30+response data in the same way. It's powered by urllib2, but it does31+all the hard work and crazy hacks for you.32+33+34 Features35 --------36 37 - Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests28 unmodified lines66 67 68 Uh oh, we're not authorized! Let's add authentication. ::69 46- >>> r = requests.get(https://httpbin.ep.io/basic-auth/user/pass', auth=('user', 'pass'))70+ >>> r = requests.get('https://httpbin.ep.io/basic-auth/user/pass', auth=('user', 'pass'))71 72 >>> r.status_code73 20074 3 unmodified lines78 >>> r.content79 '{"authenticated": true, "user": "user"}'80 81 58-59-API60----61-62-**Requests:**63-64-All request functions return a Response object (see below).65-66-If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.67-If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.68-69- HEAD Requests70- >>> requests.head(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})71- <Response [200]>72-73- GET Requests74- >>> requests.get(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})75- <Response [200]>76-77- POST Requests78- >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})79- <Response [200]>80-81- PUT Requests82- >>> requests.put(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})83- <Response [200]>84-85- PATCH Requests86- >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})87- <Response [200]>88-89- DELETE Requests90- >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})91- <Response [200]>92-93-94-**Responses:**95-96- Response.status_code97- (Integer) Received HTTP Status Code Response98-99- Response.headers100- ((CaseInsensitive) Dictionary) Received HTTP Response Headers.101-102- Response.content103- (Bytes) Received Content.104-105- Response.history106- (List of Responses) Redirection History.107-108- Response.url109- (String) URL of response. Useful for detecting redirects.110-111- Response.ok112- (Bool) True if no errors occurred during the request, and the status_code is kosher.113-114- Response.cached115- (Bool) True if Response.content is stored within the object.116-117- Response.error118- (HTTPError) If an HTTPError occurred (e.g. status of 404), Otherwise this is None.119-120- Response.raise_for_status()121- Raises HTTPError if a request is not kosher.122-123-124-**HTTP Authentication Registry:**125-126- You can register AuthObjects to automatically enable HTTP Authentication on requests that contain a registered base URL string.127-128- >>> requests.auth_manager.add_auth(url, authobject)129-130-131-82 Installation83 ------------84 85 To install requests, simply: ::25 unmodified linesmodified:test_requests.py+226 added-117 removed
11 unmodified lines12 import json13 14 import requests15 16+from requests.sessions import Session17 18 19 HTTPBIN_URL = 'http://httpbin.org/'20 HTTPSBIN_URL = 'https://httpbin.ep.io/'13 unmodified lines34 35 return HTTPSBIN_URL + '/'.join(suffix)36 37 38+SERVICES = (httpbin, httpsbin)39 40+41+42 class RequestsTestSuite(unittest.TestCase):43 """Requests test cases."""44 45 85 unmodified lines131 r = requests.patch(httpsbin('patch'))132 self.assertEqual(r.status_code, 200)133 134 131- def test_AUTH_HTTPS_200_OK_GET(self):132- auth = ('user', 'pass')133- url = httpsbin('basic-auth', 'user', 'pass')134- r = requests.get(url, auth=auth)135+ def test_AUTH_HTTP_200_OK_GET(self):136 136- self.assertEqual(r.status_code, 200)137+ for service in SERVICES:138 138- r = requests.get(url)139- self.assertEqual(r.status_code, 200)139+ auth = ('user', 'pass')140+ url = service('basic-auth', 'user', 'pass')141 141- # reset auto authentication142- requests.auth_manager.empty()142+ r = requests.get(url, auth=auth)143+ # print r.__dict__144+ self.assertEqual(r.status_code, 200)145 146 147+ r = requests.get(url)148+ self.assertEqual(r.status_code, 200)149+150+151 def test_POSTBIN_GET_POST_FILES(self):146- url = httpbin('post')147- post = requests.post(url).raise_for_status()152 149- post = requests.post(url, data={'some': 'data'})150- self.assertEqual(post.status_code, 200)153+ for service in SERVICES:154 152- post2 = requests.post(url, files={'some': open('test_requests.py')})153- self.assertEqual(post2.status_code, 200)155+ url = service('post')156+ post = requests.post(url).raise_for_status()157 155- post3 = requests.post(url, data='[{"some": "json"}]')156- self.assertEqual(post3.status_code, 200)158+ post = requests.post(url, data={'some': 'data'})159+ self.assertEqual(post.status_code, 200)160 161+ post2 = requests.post(url, files={'some': open('test_requests.py')})162+ self.assertEqual(post2.status_code, 200)163 164+ post3 = requests.post(url, data='[{"some": "json"}]')165+ self.assertEqual(post3.status_code, 200)166+167+168 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):169 161- url = httpbin('post')162- post = requests.post(url, files={'some': open('test_requests.py')}, data={'some': 'data'})163- self.assertEqual(post.status_code, 200)170+ for service in SERVICES:171 172+ url = service('post')173+ post = requests.post(url,174+ files={'some': open('test_requests.py')},175+ data={'some': 'data'})176 177+ self.assertEqual(post.status_code, 200)178+179+180 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):181 168- url = httpbin('post')182+ for service in SERVICES:183 170- post2 = requests.post(url, files={'some': open('test_requests.py')},171- headers = {'User-Agent': 'requests-tests'})184+ url = service('post')185 173- self.assertEqual(post2.status_code, 200)186+ post2 = requests.post(url,187+ files={'some': open('test_requests.py')},188+ headers = {'User-Agent': 'requests-tests'})189 190+ self.assertEqual(post2.status_code, 200)191 192+193 def test_nonzero_evaluation(self):177- r = requests.get(httpbin('status', '500'))178- self.assertEqual(bool(r), False)194 180- r = requests.get(httpbin('/'))181- self.assertEqual(bool(r), True)195+ for service in SERVICES:196 197+ r = requests.get(service('status', '500'))198+ self.assertEqual(bool(r), False)199 200+ r = requests.get(service('/'))201+ self.assertEqual(bool(r), True)202+203+204 def test_request_ok_set(self):185- r = requests.get(httpbin('status', '404'))186- self.assertEqual(r.ok, False)205 206+ for service in SERVICES:207 208+ r = requests.get(service('status', '404'))209+ self.assertEqual(r.ok, False)210+211+212 def test_status_raising(self):213 r = requests.get(httpbin('status', '404'))214 self.assertRaises(requests.HTTPError, r.raise_for_status)215 27 unmodified lines243 r = requests.get(httpbin('gzip'))244 r.content.decode('ascii')245 246 224- def test_autoauth(self):225-226- http_auth = ('user', 'pass')227- requests.auth_manager.add_auth('httpbin.org', http_auth)228-229- r = requests.get(httpbin('basic-auth', 'user', 'pass'))230- self.assertEquals(r.status_code, 200)231-232-247 def test_unicode_get(self):248 235- url = httpbin('/')249+ for service in SERVICES:250 237- requests.get(url, params={'foo': u'føø'})238- requests.get(url, params={u'føø': u'føø'})239- requests.get(url, params={'føø': 'føø'})240- requests.get(url, params={'foo': u'foo'})241- requests.get(httpbin('ø'), params={'foo': u'foo'})251+ url = service('/')252 253+ requests.get(url, params={'foo': u'føø'})254+ requests.get(url, params={u'føø': u'føø'})255+ requests.get(url, params={'føø': 'føø'})256+ requests.get(url, params={'foo': u'foo'})257+ requests.get(service('ø'), params={'foo': u'foo'})258 259+260 def test_httpauth_recursion(self):261+262 http_auth = ('user', 'BADpass')263 264+ for service in SERVICES:247- r = requests.get(httpbin('basic-auth', 'user', 'pass'), auth=http_auth)248- self.assertEquals(r.status_code, 401)265+ r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)266+ self.assertEquals(r.status_code, 401)267 268 269 def test_settings(self):270 8 unmodified lines279 requests.get(httpbin(''))280 281 282 def test_urlencoded_post_data(self):265- r = requests.post(httpbin('post'), data=dict(test='fooaowpeuf'))266- self.assertEquals(r.status_code, 200)267- self.assertEquals(r.headers['content-type'], 'application/json')268- self.assertEquals(r.url, httpbin('post'))269- rbody = json.loads(r.content)270- self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))271- self.assertEquals(rbody.get('data'), '')283 284+ for service in SERVICES:285 286+ r = requests.post(service('post'), data=dict(test='fooaowpeuf'))287+288+ self.assertEquals(r.status_code, 200)289+ self.assertEquals(r.headers['content-type'], 'application/json')290+ self.assertEquals(r.url, service('post'))291+292+ rbody = json.loads(r.content)293+294+ self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))295+ self.assertEquals(rbody.get('data'), '')296+297+298 def test_nonurlencoded_post_data(self):275- r = requests.post(httpbin('post'), data='fooaowpeuf')276- self.assertEquals(r.status_code, 200)277- self.assertEquals(r.headers['content-type'], 'application/json')278- self.assertEquals(r.url, httpbin('post'))279- rbody = json.loads(r.content)280- # Body wasn't valid url encoded data, so the server returns None as281- # "form" and the raw body as "data".282- self.assertEquals(rbody.get('form'), None)283- self.assertEquals(rbody.get('data'), 'fooaowpeuf')299 300+ for service in SERVICES:301 302+ r = requests.post(service('post'), data='fooaowpeuf')303+304+ self.assertEquals(r.status_code, 200)305+ self.assertEquals(r.headers['content-type'], 'application/json')306+ self.assertEquals(r.url, service('post'))307+308+ rbody = json.loads(r.content)309+ # Body wasn't valid url encoded data, so the server returns None as310+ # "form" and the raw body as "data".311+ self.assertEquals(rbody.get('form'), None)312+ self.assertEquals(rbody.get('data'), 'fooaowpeuf')313+314+315 def test_urlencoded_post_querystring(self):287- r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'))288- self.assertEquals(r.status_code, 200)289- self.assertEquals(r.headers['content-type'], 'application/json')290- self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))291- rbody = json.loads(r.content)292- self.assertEquals(rbody.get('form'), {}) # No form supplied293- self.assertEquals(rbody.get('data'), '')316 317+ for service in SERVICES:318 319+ r = requests.post(service('post'), params=dict(test='fooaowpeuf'))320+321+ self.assertEquals(r.status_code, 200)322+ self.assertEquals(r.headers['content-type'], 'application/json')323+ self.assertEquals(r.url, service('post?test=fooaowpeuf'))324+325+ rbody = json.loads(r.content)326+ self.assertEquals(rbody.get('form'), {}) # No form supplied327+ self.assertEquals(rbody.get('data'), '')328+329+330 def test_nonurlencoded_post_querystring(self):297- r = requests.post(httpbin('post'), params='fooaowpeuf')298- self.assertEquals(r.status_code, 200)299- self.assertEquals(r.headers['content-type'], 'application/json')300- self.assertEquals(r.url, httpbin('post?fooaowpeuf'))301- rbody = json.loads(r.content)302- self.assertEquals(rbody.get('form'), {}) # No form supplied303- self.assertEquals(rbody.get('data'), '')331 332+ for service in SERVICES:333 334+ r = requests.post(service('post'), params='fooaowpeuf')335+336+ self.assertEquals(r.status_code, 200)337+ self.assertEquals(r.headers['content-type'], 'application/json')338+ self.assertEquals(r.url, service('post?fooaowpeuf'))339+340+ rbody = json.loads(r.content)341+ self.assertEquals(rbody.get('form'), {}) # No form supplied342+ self.assertEquals(rbody.get('data'), '')343+344+345 def test_urlencoded_post_query_and_data(self):307- r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'),308- data=dict(test2="foobar"))309- self.assertEquals(r.status_code, 200)310- self.assertEquals(r.headers['content-type'], 'application/json')311- self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))312- rbody = json.loads(r.content)313- self.assertEquals(rbody.get('form'), dict(test2='foobar'))314- self.assertEquals(rbody.get('data'), '')346 347+ for service in SERVICES:348 349+ r = requests.post(350+ service('post'),351+ params=dict(test='fooaowpeuf'),352+ data=dict(test2="foobar"))353+354+ self.assertEquals(r.status_code, 200)355+ self.assertEquals(r.headers['content-type'], 'application/json')356+ self.assertEquals(r.url, service('post?test=fooaowpeuf'))357+358+ rbody = json.loads(r.content)359+ self.assertEquals(rbody.get('form'), dict(test2='foobar'))360+ self.assertEquals(rbody.get('data'), '')361+362+363 def test_nonurlencoded_post_query_and_data(self):318- r = requests.post(httpbin('post'), params='fooaowpeuf',319- data="foobar")320- self.assertEquals(r.status_code, 200)321- self.assertEquals(r.headers['content-type'], 'application/json')322- self.assertEquals(r.url, httpbin('post?fooaowpeuf'))323- rbody = json.loads(r.content)324- self.assertEquals(rbody.get('form'), None)325- self.assertEquals(rbody.get('data'), 'foobar')364 365+ for service in SERVICES:366+367+ r = requests.post(service('post'),368+ params='fooaowpeuf', data="foobar")369+370+ self.assertEquals(r.status_code, 200)371+ self.assertEquals(r.headers['content-type'], 'application/json')372+ self.assertEquals(r.url, service('post?fooaowpeuf'))373+374+ rbody = json.loads(r.content)375+376+ self.assertEquals(rbody.get('form'), None)377+ self.assertEquals(rbody.get('data'), 'foobar')378+379+380 def test_idna(self):381 r = requests.get(u'http://➡.ws/httpbin')382 assert 'httpbin' in r.url383 384+385 def test_urlencoded_get_query_multivalued_param(self):332- r = requests.get(httpbin('get'), params=dict(test=['foo','baz']))333- self.assertEquals(r.status_code, 200)334- self.assertEquals(r.url, httpbin('get?test=foo&test=baz'))386 387+ for service in SERVICES:388+389+ r = requests.get(service('get'), params=dict(test=['foo','baz']))390+ self.assertEquals(r.status_code, 200)391+ self.assertEquals(r.url, service('get?test=foo&test=baz'))392+393+394 def test_urlencoded_post_querystring_multivalued(self):337- r = requests.post(httpbin('post'), params=dict(test=['foo','baz']))338- self.assertEquals(r.status_code, 200)339- self.assertEquals(r.headers['content-type'], 'application/json')340- self.assertEquals(r.url, httpbin('post?test=foo&test=baz'))341- rbody = json.loads(r.content)342- self.assertEquals(rbody.get('form'), {}) # No form supplied343- self.assertEquals(rbody.get('data'), '')395 396+ for service in SERVICES:397+398+ r = requests.post(service('post'), params=dict(test=['foo','baz']))399+ self.assertEquals(r.status_code, 200)400+ self.assertEquals(r.headers['content-type'], 'application/json')401+ self.assertEquals(r.url, service('post?test=foo&test=baz'))402+403+ rbody = json.loads(r.content)404+ self.assertEquals(rbody.get('form'), {}) # No form supplied405+ self.assertEquals(rbody.get('data'), '')406+407+408 def test_urlencoded_post_query_multivalued_and_data(self):346- r = requests.post(httpbin('post'), params=dict(test=['foo','baz']),347- data=dict(test2="foobar",test3=['foo','baz']))348- self.assertEquals(r.status_code, 200)349- self.assertEquals(r.headers['content-type'], 'application/json')350- self.assertEquals(r.url, httpbin('post?test=foo&test=baz'))351- rbody = json.loads(r.content)352- self.assertEquals(rbody.get('form'), dict(test2='foobar',test3='foo'))353- self.assertEquals(rbody.get('data'), '')409 410+ for service in SERVICES:411 412+ r = requests.post(413+ service('post'),414+ params=dict(test=['foo','baz']),415+ data=dict(test2="foobar",test3=['foo','baz']))416+417+ self.assertEquals(r.status_code, 200)418+ self.assertEquals(r.headers['content-type'], 'application/json')419+ self.assertEquals(r.url, service('post?test=foo&test=baz'))420+ rbody = json.loads(r.content)421+ self.assertEquals(rbody.get('form'), dict(test2='foobar',test3='foo'))422+ self.assertEquals(rbody.get('data'), '')423+424+425 def test_redirect_history(self):357- r = requests.get(httpbin('redirect', '3'))358- self.assertEquals(r.status_code, 200)359- self.assertEquals(len(r.history), 3)426 361- r = requests.get(httpsbin('redirect', '3'))362- self.assertEquals(r.status_code, 200)363- self.assertEquals(len(r.history), 3)427+ for service in SERVICES:428 429+ r = requests.get(service('redirect', '3'))430+ self.assertEquals(r.status_code, 200)431+ self.assertEquals(len(r.history), 3)432+433+434+ def test_relative_redirect_history(self):435+436+ for service in SERVICES:437+438+ r = requests.get(service('relative-redirect', '3'))439+ self.assertEquals(r.status_code, 200)440+ self.assertEquals(len(r.history), 3)441+442+443+ def test_session_HTTP_200_OK_GET(self):444+445+ s = Session()446+ r = s.get(httpbin('/'))447+ self.assertEqual(r.status_code, 200)448+449+450+ def test_session_HTTPS_200_OK_GET(self):451+452+ s = Session()453+ r = s.get(httpsbin('/'))454+ self.assertEqual(r.status_code, 200)455+456+457+ def test_session_persistent_headers(self):458+459+ heads = {'User-agent': 'Mozilla/5.0'}460+461+ s = Session()462+ s.headers = heads463+ # Make 2 requests from Session object, should send header both times464+ r1 = s.get(httpbin('user-agent'))465+466+ assert heads['User-agent'] in r1.content467+ r2 = s.get(httpbin('user-agent'))468+469+ assert heads['User-agent'] in r2.content470+ self.assertEqual(r2.status_code, 200)471+472+473+474 if __name__ == '__main__':475 unittest.main()