Skip to content
Myr

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

30 files+1157 added−340 removed

added:debian/changelog+5 added
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
added:debian/compat+1 added
15
added:debian/control+13 added
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.
added:debian/docs+1 added
1docs/user/*.rst
added:debian/pyversions+1 added
12.4-
added:debian/rules+42 added
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
added:docs/community/faq.rst+43 added
1.. _faq:23Frequently Asked Questions4==========================56This part of the documentation covers common questions about Requests.78Why not Httplib2?9-----------------1011Chris Adams gave an excellent summary on12`Hacker News <http://news.ycombinator.com/item?id=2884406>`_:1314 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].2223 Disclosure: I'm listed in the requests AUTHORS file but can claim credit24 for, oh, about 0.0001% of the awesomeness.2526 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.323334Python 3 Support?35-----------------3637It's on the way. Here's a list of `supported interpreters <interpreters>`_.383940Keep-alive Support?41-------------------4243It's on the way.
added:docs/community/support.rst+37 added
1.. _support:23Support4=======56If you have a questions or issues about Requests, there are serveral options:78Send a Tweet9------------1011If your question is less than 140 characters, feel free to send a tweet to12`@kennethreitz <http://twitter.com/kennethreitz>`_.131415File an Issue16-------------1718If you notice some unexpected behavior in Requests, or want to see support19for a new feature,20`file an issue on GitHub <https://github.com/kennethreitz/requests/issues>`_.212223E-mail24------2526I'm more than happy to answer any personal or in-depth questions about27Requests. Feel free to email28`requests@kennethreitz.com <mailto:requests@kennethreitz.com>`_.293031IRC32---3334The official Freenode channel for Requests is35`#python-requests <irc://irc.freenode.net/python-requests>`_3637I'm also available as **kennethreitz** on Freenode.
added:docs/community/updates.rst+31 added
1.. _updates:23Updates4=======56If you'd like to stay up to date on the community and development of Requests,7there are serveral options:89GitHub10------1112The best way to track the development of Requests is through13`the GitHub repo <https://github.com/kennethreitz/requests>`_.1415Twitter16-------1718I often tweet about new features and releases of Requests.1920Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.21222324Mailing List25------------2627There's a low-volume mailing list for Requests. To subscribe to the28mailing list, send an email to29`requests@librelist.org <mailto:requests@librelist.org>`_.3031
added:docs/dev/authors.rst+5 added
1Authors2=======345.. include:: ../../AUTHORS
modified:docs/user/advanced.rst+137 added
1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.789Session Objects10---------------1112The Session object allows you to persist certain parameters across13requests. It also establishes a CookieJar and passes it along14to any requests made from the Session instance.1516A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920 with requests.session() as s:2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print r.content26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods::3031 headers = {'x-test': 'true'}32 auth = ('user', 'pass')3334 with requests.session(auth=auth, headers=headers) as c:3536 # both 'x-test' and 'x-test2' are sent37 c.get('http://httpbin.org/headers', header={'x-test2', 'true'})383940.. admonition:: Global Settings4142 Certain parameters are best set at the ``request.config`` level43 (e.g.. a global proxy, user agent header).444546Event Hooks47-----------4849Requests has a hook system that you can use to manipulate portions of50the request process, or signal event handling.5152Available hooks:5354``args``:55 A dictionary of the arguments being sent to Request().5657``pre_request``:58 The Request object, directly before being sent.5960``post_request``:61 The Request object, directly after being sent.6263``response``:64 The response generated from a Request.656667You can assign a hook function on a per-request basis by passing a68``{hook_name: callback_function}`` dictionary to the ``hooks`` request69paramaeter::7071 hooks=dict(args=print_url)7273That ``callback_function`` will receive a chunk of data as its first74argument.7576::7778 def print_url(args):79 print args['url']8081If an error occurs while executing your callback, a warning is given.8283If the callback function returns a value, it is assumed that it is to84replace the data that was passed in. If the function doesn't return85anything, nothing else is effected.8687Let's print some request method arguments at runtime::8889 >>> requests.get('http://httpbin', hooks=dict(args=print_url))90 http://httpbin91 <Response [200]>9293Let's hijack some arguments this time with a new callback::9495 def hack_headers(args):96 if not args[headers]:97 args['headers'] = dict()9899 args['headers'].update({'X-Testing': 'True'})100101 return args102103 hooks = dict(args=hack_headers)104 headers = dict(yo=dawg)105106And give it a try::107108 >>> 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 }123124125126Verbose Logging127---------------128129If you want to get a good look at what HTTP requests are being sent130by your application, you can turn on verbose logging.131132To do so, just configure Requests with a stream to write to::133134 >>> 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 lines
14 $ pip install requests1516or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::1718 $ easy_install install requests18 $ easy_install requests1920But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21222324Cheeseshop Mirror25-----------------2627If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <pip.kreitz.co/>`_::27If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::2829 $ pip install -i http://pip.kreitz.co/simple requests303132Get the Code33------------3435Requsts is actively developed on GitHub, where the code is35Requests is actively developed on GitHub, where the code is36`always available <https://github.com/kennethreitz/requests>`_.3738You can either clone the public repository::39
14 unmodified lines
modified:docs/user/intro.rst+9 added
1.. _introduction:23Introduction4============56Philosophy
34 unmodified lines
4142 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.434445.. _interpreters:46Python Interpreters47-------------------4849At this time, the following Python platforms are officially supported:5051* 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.56263
1 unmodified line
modified:docs/user/quickstart.rst+98 added-48 removed
1Feature Overview2================1.. _quickstart:24Requests is designed to solve a 90% use case — making simple requests. While most5HTTP libraries are extremely extensible, they often attempt to support the entire HTTP Spec.6This 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.3Quickstart4==========56.. module:: requests.models79.. _features:8Eager 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.911Requests Can:12-------------10First, make sure that:1114- 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>`141528Requests Can't:29---------------16Lets gets started with some simple use cases and examples.1731- Handle Caching32- Handle Keep-Alives1819Make a GET Request20------------------2135Quickstart36==========22Making a standard request with Requests is very simple.2324Let's get GitHub's public timeline ::2539GET Request40-----------26 r = requests.get('https://github.com/timeline.json')2728Now, we have a :class:`Response` object called ``r``. We can get all the information we need from this.2943Adding Parameters44-----------------3031Response Content32----------------3334We can read the content of the server's response::3548Adding Headers49--------------36 >>> r.content37 '[{"repository":{"open_issues":0,"url":"https://github.com/...383940Response Status Codes41---------------------4253HTTP Basic Auth54---------------43We can check the response status code::4445 >>> r.status_code46 2004757Tracking Redirects58------------------48Requests also comes with a built-in status code lookup object for easy49reference::5051 >>> r.status_code == requests.codes.ok52 True5354If we made a bad request, we can raise it with55:class:`Response.raise_for_status()`::5657 >>> _r = requests.get('http://httpbin.org/status/404')58 >>> _r.status_code59 4046063HTTP 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 FOUND6667But, since our ``status_code`` was ``200``, when we call it::6867HTTP POST (Binary Data)68-----------------------69 >>> r.raise_for_status()70 None7172All is well.7371HTTP POST (Multipart Files)72---------------------------7475Response Headers76----------------7775HTTP PUT76--------78We can view the server's response headers with a simple Python dictionary79interface::8081 >>> 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 }9279HTTP DELETE80-----------93The dictionary is special, though: it's made just for HTTP headers. According to `RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP94Headers are case-insensitive.9596So, we can access the headers using any capitalization we want::9783HTTP HEAD84---------98 >>> r.headers['Content-Type']99 'application/json; charset=utf-8'100101 >>> r.headers.get('content-type')102 'application/json; charset=utf-8'103104If a header doesn't exist in the Response, its value defaults to ``None``::105106 >>> r.headers['X-Random']107 None108109110Cookies111-------112113If a response contains some Cookies, you can get quick access to them::114115 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'116 >>> r = requests.get(url)117118 >>> print r.cookies119 {'requests-is': 'awesome'}120121The underlying CookieJar is also available for more advanced handing::122123 >>> r.request.cookiejar124 <cookielib.CookieJar>125126To send your own cookies to the server, you can use the ``cookies``127parameter::128129 >>> url = 'http://httpbin.org/cookies'130 >>> cookies = dict(cookies_are='working')131132 >>> r = requests.get(url, cookies=cookies)133 >>> r.content134 '{"cookies": {"cookies_are": "working"}}'
modified:docs/api.rst+1 added-12 removed
20 unmodified lines
21.. autofunction:: post22.. autofunction:: put23.. autofunction:: patch24.. autofunction:: delete25.. autofunction:: request262627-----------282930.. autoclass:: requests.models.Response
18 unmodified lines
49These items are an internal component to Requests, and should never be50seen by the end user (developer). This part of the API documentation51exists for those who are extending the functionality of Requests.5253Functions54~~~~~~~~~5556.. autofunction:: request5753Classes54~~~~~~~5556.. autoclass:: requests.models.Request57 :inherited-members:6364Structures65~~~~~~~~~~6667.. autoclass:: requests.structures.CaseInsensitiveDict68 :inherited-members:
modified:docs/conf.py+1 added-1 removed
153 unmodified lines
154# If true, the index is split into individual pages for each letter.155#html_split_index = False156157# If true, links to the reST sources are added to the pages.158html_show_sourcelink = True158html_show_sourcelink = False159160# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.161html_show_sphinx = False162
82 unmodified lines
modified:docs/index.rst+29 added-7 removed
11 unmodified lines
1213Most existing Python modules for sending HTTP requests are extremely verbose14and cumbersome. Python's builtin **urllib2** module provides most of15the HTTP capabilities you should need, but the api is thoroughly **broken**.16It requires an *enormous* amount of work (even method overrides) to perform the simplest of tasks.16It requires an *enormous* amount of work (even method overrides) to perform17the simplest of tasks.1819Things shouldn’t be this way. Not in Python.2021::2223 >>> 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 ...3031See `the same code, without Requests <https://gist.github.com/973705>`_.3233Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,
7 unmodified lines
4142`Twitter, Inc <http://twitter.com>`_ uses Requests internally.4344**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.4748**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.5152**Rich Leland**53 Requests is awesome. That is all.5455**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!585960User Guide61----------6257This 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.63This part of the documentation, which is mostly prose, begins with some64background information about Requests, then focuses on step-by-step65instructions for getting the most out of Requests.6667.. toctree::68 :maxdepth: 26970 user/intro71 user/install64.. user/quickstart72 user/quickstart73 user/advanced747576Community Guide77-----------------7879This part of the documentation, which is mostly prose, details the80Requests ecosystem and community.8182.. toctree::83 :maxdepth: 28485 community/faq86 community/support87 community/updates8889API Documentation90-----------------9192If you are looking for information on a specific function, class or method,
15 unmodified lines
108 :maxdepth: 2109110 dev/internals111 dev/todo112 dev/authors
modified:requests/api.py+50 added-50 removed
10 unmodified lines
1112"""1314import config15from .models import Request, Response, AuthManager, AuthObject, auth_manager15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict1920from urlparse import urlparse2122__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')2324def 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):2724 """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.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`.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 """4339 r = Request(44 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,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 )6263 # Arguments manipulation hook.64 args = dispatch_hook('args', hooks, args)6566 r = Request(**args)6768 # 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.response818258def get(url,59 params=None, headers=None, cookies=None, auth=None, timeout=None,60 proxies=None):83def get(url, **kwargs):8485 """Sends a GET request. Returns :class:`Response` object.8687 :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 """9573 return request('GET', url,74 params=params, headers=headers, cookies=cookies, auth=auth,75 timeout=timeout, proxies=proxies)96 return request('GET', url, **kwargs)979878def head(url,79 params=None, headers=None, cookies=None, auth=None, timeout=None,80 proxies=None):99def head(url, **kwargs):100101 """Sends a HEAD request. Returns :class:`Response` object.102103 :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 """11193 return request('HEAD', url,94 params=params, headers=headers, cookies=cookies, auth=auth,95 timeout=timeout, proxies=proxies)112 return request('HEAD', url, **kwargs)11311498def post(url,99 data='', headers=None, files=None, cookies=None, auth=None, timeout=None,100 allow_redirects=False, params=None, proxies=None):115def post(url, data='', **kwargs):116117 """Sends a POST request. Returns :class:`Response` object.118119 :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 """130116 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)132133122def put(url, data='', headers=None, files=None, cookies=None, auth=None,123 timeout=None, allow_redirects=False, params=None, proxies=None):134def put(url, data='', **kwargs):135 """Sends a PUT request. Returns :class:`Response` object.136137 :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 """148138 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)150151144def patch(url, data='', headers=None, files=None, cookies=None, auth=None,145 timeout=None, allow_redirects=False, params=None, proxies=None):152def patch(url, data='', **kwargs):153 """Sends a PATCH request. Returns :class:`Response` object.154155 :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 """166160 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)168169166def delete(url,167 params=None, headers=None, cookies=None, auth=None, timeout=None,168 allow_redirects=False, proxies=None):170def delete(url, **kwargs):171172 """Sends a DELETE request. Returns :class:`Response` object.173174 :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 """183182 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 lines
11class Settings(object):12 _singleton = {}1314 # attributes with defaults15 __attrs__ = ('timeout', 'verbose')15 __attrs__ = []1617 def __init__(self, **kwargs):18 super(Settings, self).__init__()19
32 unmodified lines
52 except AttributeError:53 return None54 return object.__getattribute__(self, key)555657settings = Settings()5859settings.base_headers = {'User-Agent': 'python-requests.org'}58settings.accept_gzip = True60settings.accept_gzip = True61settings.proxies = None62settings.verbose = None63settings.timeout = None6465#: Use socket.setdefaulttimeout() as fallback?66settings.timeout_fallback = True
modified:requests/core.py+5 added-3 removed
10 unmodified lines
1112"""1314__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'202122from models import HTTPError, auth_manager22from models import HTTPError23from api import *24from exceptions import *25from sessions import session26from status_codes import codes27from config import settings
added:requests/hooks.py+40 added
1# -*- coding: utf-8 -*-23"""4requests.hooks5~~~~~~~~~~~~~~67This module provides the capabilities for the Requests hooks system.89Available hooks:1011``args``:12 A dictionary of the arguments being sent to Request().1314``pre_request``:15 The Request object, directly before being sent.1617``post_request``:18 The Request object, directly after being sent.1920``response``:21 The response generated from a Request.2223"""2425import warnings262728def dispatch_hook(key, hooks, hook_data):29 """Dipatches a hook dictionary on a given peice of data."""3031 hooks = hooks or dict()3233 if key in hooks:34 try:35 return hooks.get(key).__call__(hook_data) or hook_data3637 except Exception, why:38 warnings.warn(str(why))3940 return hook_data
modified:requests/models.py+62 added-18 removed
10 unmodified lines
11import socket12import zlib1314from urllib2 import HTTPError15from urlparse import urlparse, urlunparse15from urlparse import urlparse, urlunparse, urljoin16from datetime import datetime1718from .config import settings19from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20from .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, InvalidMethod252627REDIRECT_STATI = (301, 302, 303, 307)
10 unmodified lines
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):4141 socket.setdefaulttimeout(timeout)42 #: Float describ the timeout of the request.43 # (Use socket.setdefaulttimeout() as fallback)44 self.timeout = timeout4546 #: Request URL.47 self.url = url4849 #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.50 self.headers = headers5152 #: Dictionary of files to multipart upload (``{filename: content}``).53 self.files = files5455 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.56 self.method = method5758 #: Dictionary or byte of request body data to attach to the59 #: :class:`Request <models.Request>`.60 self.data = None6162 #: Dictionary or byte of querystring data to attach to the63 #: :class:`Request <models.Request>`.64 self.params = None6566 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history67 #: and HTTPError storage).68 self.redirect = redirect6970 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)71 self.allow_redirects = allow_redirects7273 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})74 self.proxies = proxies7576 self.data, self._enc_data = self._encode_params(data)
6 unmodified lines
83 if isinstance(auth, (list, tuple)):84 auth = AuthObject(*auth)85 if not auth:86 auth = auth_manager.get_auth(self.url)8788 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89 self.auth = auth9091 #: CookieJar to attach to :class:`Request <models.Request>`.92 self.cookiejar = cookiejar9394 #: True if Request has been sent.95 self.sent = False9697
42 unmodified lines
140 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))141142 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 lines
172173 return opener.open174175161 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."""178179 def build(resp):180
3 unmodified lines
184 try:185 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))186 response.read = resp.read187 response.close = resp.close188189 if self.cookiejar:190191 response.cookies = dict_from_cookiejar(self.cookiejar)192193194 except AttributeError:195 pass196197 if is_error:198 response.error = resp199200 response.url = getattr(resp, 'url', None)201202 return response203
16 unmodified lines
220 url = r.headers['location']221222 # 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)225226 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4227 if r.status_code is 303:228 method = 'GET'
10 unmodified lines
239240 r.history = history241242 self.response = r243 self.response.request = self244245246 @staticmethod247 def _encode_params(data):
18 unmodified lines
266 return data, data267268269 def _build_url(self):247 """Build the actual URL to use"""270 """Build the actual URL to use."""271272 # Support for unicode domain names.273 parsed_url = list(urlparse(self.url))274 parsed_url[1] = parsed_url[1].encode('idna')
17 unmodified lines
292293 :param anyway: If True, request will be sent, even if it has294 already been sent.295 """296297 self._checks()298 success = False299300 # Logging
20 unmodified lines
321 else:322 req = _Request(url, data=self._enc_data, method=self.method)323324 if self.headers:301 req.headers.update(self.headers)325 for k,v in self.headers.iteritems():326 req.add_header(k, v)327328 if not self.sent or anyway:329330 try:331 opener = self._get_opener()307 resp = opener(req)332 try:333334 resp = opener(req, timeout=self.timeout)335336 except TypeError, err:337 # timeout argument is new since Python v2.6338 if not 'timeout' in str(err):339 raise340341 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)345346 resp = opener(req)347348 if settings.timeout_fallback:349 # restore gobal timeout350 socket.setdefaulttimeout(old_timeout)351352 if self.cookiejar is not None:353 self.cookiejar.extract_cookies(resp, req)354355 except (urllib2.HTTPError, urllib2.URLError), why:356 if hasattr(why, 'reason'):357 if isinstance(why.reason, socket.timeout):358 why = Timeout(why)359317 self._build_response(why)318 if not self.redirect:319 self.response.error = why360 self._build_response(why, is_error=True)361362363 else:364 self._build_response(resp)365 self.response.ok = True366325 self.response.cached = False326 else:327 self.response.cached = True367368 self.sent = self.response.ok369331370 return self.sent371372373
20 unmodified lines
394 #: 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 = None406407408 def __repr__(self):409 return '<Response [%s]>' % (self.status_code)
96 unmodified lines
506507508 def reduce_uri(self, uri, default_port=True):509 """Accept authority or URI and extract only the authority and path."""510511 # note HTTP URLs do not have a userinfo component512 parts = urllib2.urlparse.urlsplit(uri)513514 if parts[1]:515 # URI516 scheme = parts[0]517 authority = parts[1]
2 unmodified lines
520 # host or host:port521 scheme = None522 authority = uri523 path = '/'524525 host, port = urllib2.splitport(authority)526527 if default_port and port is None and scheme is not None:528 dport = {"http": 80,529 "https": 443,530 }.get(scheme)
80 unmodified lines
added:requests/sessions.py+84 added
1# -*- coding: utf-8 -*-23"""4requests.session5~~~~~~~~~~~~~~~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_cookiejar16171819class Session(object):20 """A Requests session."""2122 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']232425 def __init__(self, **kwargs):2627 # Set up a CookieJar to be used by default28 self.cookies = cookielib.FileCookieJar()2930 # 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()363738 def __repr__(self):39 return '<requests-client at 0x%x>' % (id(self))4041 def __enter__(self):42 return self4344 def __exit__(self, *args):45 # print args46 pass474849 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 """5455 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())6263 # 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 )6970 if kwargs.get('headers', None) and inst_attrs.get('headers', None):71 kwargs['headers'].update(inst_attrs['headers'])7273 return func(*args, **kwargs)74 return wrapper_func7576 # Map and decorate each function available in requests.api77 map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),78 api.__all__)798081def session(**kwargs):82 """Returns a :class:`Session` for context-managment."""8384 return Session(**kwargs)
added:requests/status_codes.py+83 added
1# -*- coding: utf-8 -*-23from .structures import LookupDict45_codes = {67 # 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',),2223 # 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'),3334 # 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',),6364 # 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}7677codes = LookupDict(name='status_codes')7879for (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 lines
44 if key in self:45 return self[key]46 else:47 return default4849class LookupDict(dict):50 """Dictionary lookup object."""5152 def __init__(self, name=None):53 self.name = name54 super(LookupDict, self).__init__()5556 def __repr__(self):57 return '<lookup \'%s\'>' % (self.name)5859 def __getitem__(self, key):60 # We allow fall-through here, so values default to None6162 return self.__dict__.get(key, None)6364 def get(self, key, default=None):65 return self.__dict__.get(key, default)
added:requests/utils.py+72 added
1# -*- coding: utf-8 -*-23"""4requests.utils5~~~~~~~~~~~~~~67This module provides utlity functions that are used within Requests8that are also useful for external consumption.910"""1112import cookielib131415def dict_from_cookiejar(cookiejar):16 """Returns a key/value dictionary from a CookieJar."""1718 cookie_dict = {}1920 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.value2526 return cookie_dict272829def cookiejar_from_dict(cookie_dict):30 """Returns a CookieJar from a key/value dictionary."""3132 # return cookiejar if one was passed in33 if isinstance(cookie_dict, cookielib.CookieJar):34 return cookie_dict3536 # create cookiejar37 cj = cookielib.CookieJar()3839 cj = add_dict_to_cookiejar(cj, cookie_dict)4041 return cj424344def add_dict_to_cookiejar(cj, cookie_dict):45 """Returns a CookieJar from a key/value dictionary."""4647 for k, v in cookie_dict.items():4849 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 )6869 # add cookie to cookiejar70 cj.set_cookie(cookie)7172 return cj
modified:AUTHORS+6 added-1 removed
27 unmodified lines
28- 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
1History2-------3450.6.0 (2011-08-17)6++++++++++++++++++78* 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* Bugfixes19200.5.1 (2011-07-23)21++++++++++++++++++2223* International Domain Name Support!
127 unmodified lines
modified:README.rst+28 added-78 removed
1Requests: HTTP for Humans2=========================34Most 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).4Requests is an ISC Licensed HTTP library, written in Python, for human5beings.66But this one's different. This one's going to be awesome. And simple.7Most existing Python modules for sending HTTP requests are extremely8verbose and cumbersome. Python's builtin urllib2 module provides most of9the HTTP capabilities you should need, but the api is thoroughly broken.10It requires an enormous amount of work (even method overrides) to11perform the simplest of tasks.128Really simple.13Things shouldn't be this way. Not in Python.1415::1617 >>> 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 ...2425See `the same code, without Requests <https://gist.github.com/973705>`_.2627Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,28**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,29multipart files, and parameters with simple Python dictionaries, and access the30response data in the same way. It's powered by urllib2, but it does31all the hard work and crazy hacks for you.323334Features35--------3637- Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests
28 unmodified lines
666768Uh oh, we're not authorized! Let's add authentication. ::6946 >>> 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'))7172 >>> r.status_code73 20074
3 unmodified lines
78 >>> r.content79 '{"authenticated": true, "user": "user"}'80815859API60---6162**Requests:**6364All request functions return a Response object (see below).6566If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.67If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.6869 HEAD Requests70 >>> requests.head(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})71 <Response [200]>7273 GET Requests74 >>> requests.get(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})75 <Response [200]>7677 POST Requests78 >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})79 <Response [200]>8081 PUT Requests82 >>> requests.put(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})83 <Response [200]>8485 PATCH Requests86 >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})87 <Response [200]>8889 DELETE Requests90 >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})91 <Response [200]>929394**Responses:**9596 Response.status_code97 (Integer) Received HTTP Status Code Response9899 Response.headers100 ((CaseInsensitive) Dictionary) Received HTTP Response Headers.101102 Response.content103 (Bytes) Received Content.104105 Response.history106 (List of Responses) Redirection History.107108 Response.url109 (String) URL of response. Useful for detecting redirects.110111 Response.ok112 (Bool) True if no errors occurred during the request, and the status_code is kosher.113114 Response.cached115 (Bool) True if Response.content is stored within the object.116117 Response.error118 (HTTPError) If an HTTPError occurred (e.g. status of 404), Otherwise this is None.119120 Response.raise_for_status()121 Raises HTTPError if a request is not kosher.122123124**HTTP Authentication Registry:**125126 You can register AuthObjects to automatically enable HTTP Authentication on requests that contain a registered base URL string.127128 >>> requests.auth_manager.add_auth(url, authobject)12913013182Installation83------------8485To install requests, simply: ::
25 unmodified lines
modified:test_requests.py+226 added-117 removed
11 unmodified lines
12 import json1314import requests1516from requests.sessions import Session171819HTTPBIN_URL = 'http://httpbin.org/'20HTTPSBIN_URL = 'https://httpbin.ep.io/'
13 unmodified lines
3435 return HTTPSBIN_URL + '/'.join(suffix)363738SERVICES = (httpbin, httpsbin)39404142class RequestsTestSuite(unittest.TestCase):43 """Requests test cases."""4445
85 unmodified lines
131 r = requests.patch(httpsbin('patch'))132 self.assertEqual(r.status_code, 200)133134131 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):136136 self.assertEqual(r.status_code, 200)137 for service in SERVICES:138138 r = requests.get(url)139 self.assertEqual(r.status_code, 200)139 auth = ('user', 'pass')140 url = service('basic-auth', 'user', 'pass')141141 # 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)145146147 r = requests.get(url)148 self.assertEqual(r.status_code, 200)149150151 def test_POSTBIN_GET_POST_FILES(self):146 url = httpbin('post')147 post = requests.post(url).raise_for_status()152149 post = requests.post(url, data={'some': 'data'})150 self.assertEqual(post.status_code, 200)153 for service in SERVICES:154152 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()157155 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)160161 post2 = requests.post(url, files={'some': open('test_requests.py')})162 self.assertEqual(post2.status_code, 200)163164 post3 = requests.post(url, data='[{"some": "json"}]')165 self.assertEqual(post3.status_code, 200)166167168 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):169161 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:171172 url = service('post')173 post = requests.post(url,174 files={'some': open('test_requests.py')},175 data={'some': 'data'})176177 self.assertEqual(post.status_code, 200)178179180 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):181168 url = httpbin('post')182 for service in SERVICES:183170 post2 = requests.post(url, files={'some': open('test_requests.py')},171 headers = {'User-Agent': 'requests-tests'})184 url = service('post')185173 self.assertEqual(post2.status_code, 200)186 post2 = requests.post(url,187 files={'some': open('test_requests.py')},188 headers = {'User-Agent': 'requests-tests'})189190 self.assertEqual(post2.status_code, 200)191192193 def test_nonzero_evaluation(self):177 r = requests.get(httpbin('status', '500'))178 self.assertEqual(bool(r), False)194180 r = requests.get(httpbin('/'))181 self.assertEqual(bool(r), True)195 for service in SERVICES:196197 r = requests.get(service('status', '500'))198 self.assertEqual(bool(r), False)199200 r = requests.get(service('/'))201 self.assertEqual(bool(r), True)202203204 def test_request_ok_set(self):185 r = requests.get(httpbin('status', '404'))186 self.assertEqual(r.ok, False)205206 for service in SERVICES:207208 r = requests.get(service('status', '404'))209 self.assertEqual(r.ok, False)210211212 def test_status_raising(self):213 r = requests.get(httpbin('status', '404'))214 self.assertRaises(requests.HTTPError, r.raise_for_status)215
27 unmodified lines
243 r = requests.get(httpbin('gzip'))244 r.content.decode('ascii')245246224 def test_autoauth(self):225226 http_auth = ('user', 'pass')227 requests.auth_manager.add_auth('httpbin.org', http_auth)228229 r = requests.get(httpbin('basic-auth', 'user', 'pass'))230 self.assertEquals(r.status_code, 200)231232247 def test_unicode_get(self):248235 url = httpbin('/')249 for service in SERVICES:250237 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('/')252253 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'})258259260 def test_httpauth_recursion(self):261262 http_auth = ('user', 'BADpass')263264 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)267268269 def test_settings(self):270
8 unmodified lines
279 requests.get(httpbin(''))280281282 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'), '')283284 for service in SERVICES:285286 r = requests.post(service('post'), data=dict(test='fooaowpeuf'))287288 self.assertEquals(r.status_code, 200)289 self.assertEquals(r.headers['content-type'], 'application/json')290 self.assertEquals(r.url, service('post'))291292 rbody = json.loads(r.content)293294 self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))295 self.assertEquals(rbody.get('data'), '')296297298 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')299300 for service in SERVICES:301302 r = requests.post(service('post'), data='fooaowpeuf')303304 self.assertEquals(r.status_code, 200)305 self.assertEquals(r.headers['content-type'], 'application/json')306 self.assertEquals(r.url, service('post'))307308 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')313314315 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'), '')316317 for service in SERVICES:318319 r = requests.post(service('post'), params=dict(test='fooaowpeuf'))320321 self.assertEquals(r.status_code, 200)322 self.assertEquals(r.headers['content-type'], 'application/json')323 self.assertEquals(r.url, service('post?test=fooaowpeuf'))324325 rbody = json.loads(r.content)326 self.assertEquals(rbody.get('form'), {}) # No form supplied327 self.assertEquals(rbody.get('data'), '')328329330 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'), '')331332 for service in SERVICES:333334 r = requests.post(service('post'), params='fooaowpeuf')335336 self.assertEquals(r.status_code, 200)337 self.assertEquals(r.headers['content-type'], 'application/json')338 self.assertEquals(r.url, service('post?fooaowpeuf'))339340 rbody = json.loads(r.content)341 self.assertEquals(rbody.get('form'), {}) # No form supplied342 self.assertEquals(rbody.get('data'), '')343344345 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'), '')346347 for service in SERVICES:348349 r = requests.post(350 service('post'),351 params=dict(test='fooaowpeuf'),352 data=dict(test2="foobar"))353354 self.assertEquals(r.status_code, 200)355 self.assertEquals(r.headers['content-type'], 'application/json')356 self.assertEquals(r.url, service('post?test=fooaowpeuf'))357358 rbody = json.loads(r.content)359 self.assertEquals(rbody.get('form'), dict(test2='foobar'))360 self.assertEquals(rbody.get('data'), '')361362363 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')364365 for service in SERVICES:366367 r = requests.post(service('post'),368 params='fooaowpeuf', data="foobar")369370 self.assertEquals(r.status_code, 200)371 self.assertEquals(r.headers['content-type'], 'application/json')372 self.assertEquals(r.url, service('post?fooaowpeuf'))373374 rbody = json.loads(r.content)375376 self.assertEquals(rbody.get('form'), None)377 self.assertEquals(rbody.get('data'), 'foobar')378379380 def test_idna(self):381 r = requests.get(u'http://➡.ws/httpbin')382 assert 'httpbin' in r.url383384385 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'))386387 for service in SERVICES:388389 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'))392393394 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'), '')395396 for service in SERVICES:397398 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'))402403 rbody = json.loads(r.content)404 self.assertEquals(rbody.get('form'), {}) # No form supplied405 self.assertEquals(rbody.get('data'), '')406407408 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'), '')409410 for service in SERVICES:411412 r = requests.post(413 service('post'),414 params=dict(test=['foo','baz']),415 data=dict(test2="foobar",test3=['foo','baz']))416417 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'), '')423424425 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)426361 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:428429 r = requests.get(service('redirect', '3'))430 self.assertEquals(r.status_code, 200)431 self.assertEquals(len(r.history), 3)432433434 def test_relative_redirect_history(self):435436 for service in SERVICES:437438 r = requests.get(service('relative-redirect', '3'))439 self.assertEquals(r.status_code, 200)440 self.assertEquals(len(r.history), 3)441442443 def test_session_HTTP_200_OK_GET(self):444445 s = Session()446 r = s.get(httpbin('/'))447 self.assertEqual(r.status_code, 200)448449450 def test_session_HTTPS_200_OK_GET(self):451452 s = Session()453 r = s.get(httpsbin('/'))454 self.assertEqual(r.status_code, 200)455456457 def test_session_persistent_headers(self):458459 heads = {'User-agent': 'Mozilla/5.0'}460461 s = Session()462 s.headers = heads463 # Make 2 requests from Session object, should send header both times464 r1 = s.get(httpbin('user-agent'))465466 assert heads['User-agent'] in r1.content467 r2 = s.get(httpbin('user-agent'))468469 assert heads['User-agent'] in r2.content470 self.assertEqual(r2.status_code, 200)471472473474if __name__ == '__main__':475 unittest.main()