Skip to content
Myr

Merge remote-tracking branch 'upstream/develop' into develop

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Mike Waldner · committed by Mike Waldner · parents c56acf0, 75027f9 · Browse files · 25 files+1066 added−314 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

25 files+1066 added−314 removed

  • other:+1066 added−314 removed

25 files+1066 added−314 removed

added:docs/community/faq.rst+67 added
1.. _faq:23Frequently Asked Questions4==========================56This part of the documentation answers common questions about Requests.78Encoded Data?9-------------1011Requests automatically decompresses gzip-encoded responses, and does12it's best to decodes response content to unicode when possible.1314You can get direct access to the raw response (and even the socket),15if needed as well.161718Custom User-Agents?19-------------------2021Requests allows you to easily override User-Agent strings, along with22any other HTTP Header.232425Why not Httplib2?26-----------------2728Chris Adams gave an excellent summary on29`Hacker News <http://news.ycombinator.com/item?id=2884406>`_:3031 httplib2 is part of why you should use requests: it's far more respectable32 as a client but not as well documented and it still takes way too much code33 for basic operations. I appreciate what httplib2 is trying to do, that34 there's a ton of hard low-level annoyances in building a modern HTTP35 client, but really, just use requests instead. Kenneth Reitz is very36 motivated and he gets the degree to which simple things should be simple37 whereas httplib2 feels more like an academic exercise than something38 people should use to build production systems[1].3940 Disclosure: I'm listed in the requests AUTHORS file but can claim credit41 for, oh, about 0.0001% of the awesomeness.4243 1. http://code.google.com/p/httplib2/issues/detail?id=96 is a good example:44 an annoying bug which affect many people, there was a fix available for45 months, which worked great when I applied it in a fork and pounded a couple46 TB of data through it, but it took over a year to make it into trunk and47 even longer to make it onto PyPI where any other project which required "48 httplib2" would get the working version.495051Python 3 Support?52-----------------5354It's on the way. Here's a list of `supported interpreters <interpreters>`_.555657Keep-alive Support?58-------------------5960It's on the way.616263Proxy Support?64--------------6566You bet!67
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+30 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.212223Mailing List24------------2526There's a low-volume mailing list for Requests. To subscribe to the27mailing list, send an email to28`requests@librelist.org <mailto:requests@librelist.org>`_.2930
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', headers={'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`` request69parameter::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+6 added-3 removed
1 unmodified line
23Installation4============56This part of the documentation covers the installation of Requests. The first step to using any software package is getting it properly installed.6This part of the documentation covers the installation of Requests.7The first step to using any software package is getting it properly installed.8910Distribute & Pip11----------------
12 unmodified lines
2425Cheeseshop Mirror26-----------------2727If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::28If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's29personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::3031 $ pip install -i http://pip.kreitz.co/simple requests3233
15 unmodified lines
4950 $ curl -O https://github.com/kennethreitz/requests/zipball/master515251Once you have a copy of the source, you can embed it in your Python package, or install it into your site-packages easily::53Once you have a copy of the source, you can embed it in your Python package,54or install it into your site-packages easily::5556 $ python setup.py install
modified:docs/user/intro.rst+18 added-3 removed
1.. _introduction:23Introduction4============56Philosophy
13 unmodified lines
2021ISC License22-----------2324A large number of open source projects you find today are `GPL Licensed`_.25While the GPL has its time and place, it should most certainly not be your26go-to license for your next open source project.2723A large number of open source projects you find today are `GPL Licensed`_. While the GPL has its time and place, it should most certainly not be your go-to license for your next open source project.28A project that is released as GPL cannot be used in any commercial product29without the product itself also being offered as open source.3025A project that is released as GPL cannot be used in any commercial product without the product itself also being offered as open source. The MIT, BSD, ISC, and Apache2 licenses are great alternatives to the GPL that allow your open-source software to be used freely in proprietary, closed-source software.31The MIT, BSD, ISC, and Apache2 licenses are great alternatives to the GPL32that allow your open-source software to be used freely in proprietary,33closed-source software.3435Requests is released under terms of `The ISC License`_.3637.. _`GPL Licensed`: http://www.opensource.org/licenses/gpl-license.php
9 unmodified lines
4748 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.495051.. _interpreters:52Python Interpreters53-------------------5455At this time, the following Python platforms are officially supported:5657* cPython 2.558* cPython 2.5.559* cPython 2.5.660* cPython 2.661* cPython 2.6.662* cPython 2.6.763* cPython 2.764* cPython 2.7.165* cPython 2.7.266* PyPy-c 1.467* PyPy-c 1.5686955Support for Python 3.x is planned.70Support for Python 3.x is planned.
modified:docs/user/quickstart.rst+102 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 started9with Requests. This assumes you already have Requests installed. If you do not,10head over to the :ref:`Installation <install>` section.1111Requests Can:12-------------12First, make sure that:1314- 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 & Gevent14* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`161728Requests Can't:29---------------18Lets gets started with some simple use cases and examples.1931- Handle Caching32- Handle Keep-Alives2021Make a GET Request22------------------2335Quickstart36==========24Making a standard request with Requests is very simple.2526Let's get GitHub's public timeline ::2739GET Request40-----------28 r = requests.get('https://github.com/timeline.json')2930Now, we have a :class:`Response` object called ``r``. We can get all the31information we need from this.3243Adding Parameters44-----------------3334Response Content35----------------3637We can read the content of the server's response::3848Adding Headers49--------------39 >>> r.content40 '[{"repository":{"open_issues":0,"url":"https://github.com/...414243Response Status Codes44---------------------4553HTTP Basic Auth54---------------46We can check the response status code::4748 >>> r.status_code49 2005057Tracking Redirects58------------------51Requests also comes with a built-in status code lookup object for easy52reference::5354 >>> r.status_code == requests.codes.ok55 True5657If we made a bad request, we can raise it with58:class:`Response.raise_for_status()`::5960 >>> _r = requests.get('http://httpbin.org/status/404')61 >>> _r.status_code62 4046363HTTP POST (Form Data)64---------------------64 >>> _r.raise_for_status()65 Traceback (most recent call last):66 File "requests/models.py", line 394, in raise_for_status67 raise self.error68 urllib2.HTTPError: HTTP Error 404: NOT FOUND6970But, since our ``status_code`` was ``200``, when we call it::7167HTTP POST (Binary Data)68-----------------------72 >>> r.raise_for_status()73 None7475All is well.7671HTTP POST (Multipart Files)72---------------------------7778Response Headers79----------------8075HTTP PUT76--------81We can view the server's response headers with a simple Python dictionary82interface::8384 >>> r.headers85 {86 'status': '200 OK',87 'content-encoding': 'gzip',88 'transfer-encoding': 'chunked',89 'connection': 'close',90 'server': 'nginx/1.0.4',91 'x-runtime': '148ms',92 'etag': '"e1ca502697e5c9317743dc078f67693f"',93 'content-type': 'application/json; charset=utf-8'94 }9579HTTP DELETE80-----------96The dictionary is special, though: it's made just for HTTP headers. According to97`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP98Headers are case-insensitive.99100So, we can access the headers using any capitalization we want::10183HTTP HEAD84---------102 >>> r.headers['Content-Type']103 'application/json; charset=utf-8'104105 >>> r.headers.get('content-type')106 'application/json; charset=utf-8'107108If a header doesn't exist in the Response, its value defaults to ``None``::109110 >>> r.headers['X-Random']111 None112113114Cookies115-------116117If a response contains some Cookies, you can get quick access to them::118119 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'120 >>> r = requests.get(url)121122 >>> print r.cookies123 {'requests-is': 'awesome'}124125The underlying CookieJar is also available for more advanced handling::126127 >>> r.request.cookiejar128 <cookielib.CookieJar>129130To send your own cookies to the server, you can use the ``cookies``131parameter::132133 >>> url = 'http://httpbin.org/cookies'134 >>> cookies = dict(cookies_are='working')135136 >>> r = requests.get(url, cookies=cookies)137 >>> r.content138 '{"cookies": {"cookies_are": "working"}}'
modified:docs/api.rst+39 added-18 removed
11 unmodified lines
1213Main Interface14--------------1516All of Request's functionality can be accessed by these 6 methods. They17all return a :class:`Response <models.Response>` object.16All of Request's functionality can be accessed by these 7 methods.17They all return an instance of the :class:`Response <Response>` object.1819.. autofunction:: request20.. autofunction:: head21.. autofunction:: get22.. autofunction:: post23.. autofunction:: put
3 unmodified lines
2728-----------293030.. autoclass:: requests.models.Response31.. autoclass:: Response32 :inherited-members:333434Exceptions35----------3537.. autoexception:: HTTPError36Utilities37---------3839.. autoexception:: RequestException39These functions are used internally, but may be useful outside of40Requests.4141.. autoexception:: requests.models.AuthenticationError42.. autoexception:: requests.models.URLRequired43.. autoexception:: requests.models.InvalidMethod42.. module:: requests.utils4344Cookies45~~~~~~~4647.. autofunction:: dict_from_cookiejar48.. autofunction:: cookiejar_from_dict49.. autofunction:: add_dict_to_cookiejar5051Encodings52~~~~~~~~~5354.. autofunction:: get_encodings_from_content55.. autofunction:: get_encoding_from_headers56.. autofunction:: get_unicode_from_response57.. autofunction:: decode_gzip585960Internals61---------6263These items are an internal component to Requests, and should never be64seen by the end user (developer). This part of the API documentation65exists for those who are extending the functionality of Requests.6653Functions54~~~~~~~~~67Exceptions68~~~~~~~~~~6956.. autofunction:: request70.. module:: requests7172.. autoexception:: HTTPError7374.. autoexception:: RequestException7576.. autoexception:: AuthenticationError77.. autoexception:: URLRequired78.. autoexception:: InvalidMethod79.. autoexception:: TooManyRedirects80818283Classes84~~~~~~~8561.. autoclass:: requests.models.Request86.. autoclass:: requests.Request87 :inherited-members:8864Structures65~~~~~~~~~~8967.. 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+26 added-6 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::
19 unmodified lines
4142`Twitter, Inc <http://twitter.com>`_ uses Requests internally.4344**Daniel Greenfeld**44 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**47 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**53 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----------6259This 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/install66.. 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+45 added-59 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,23 timeout=None, allow_redirects=False, proxies=None):26 timeout=None, allow_redirects=False, proxies=None, hooks=None):2725 """Constructs and sends a :class:`Request <models.Request>`. Returns :class:`Response <models.Response>` object.28 """Constructs and sends a :class:`Request <Request>`.29 Returns :class:`Response <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`.32 :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 """4340 r = Request(44 method = str(method).upper()4546 if cookies is None:47 cookies = {}4849 cookies = cookiejar_from_dict(cookies)5051 args = dict(52 method = method,53 url = url,54 data = data,55 params = params,56 headers = headers,57 cookiejar = cookies,58 files = files,48 auth = auth or auth_manager.get_auth(url),59 auth = auth,60 timeout = timeout or config.settings.timeout,61 allow_redirects = allow_redirects,51 proxies = proxies or config.settings.proxies62 proxies = proxies or config.settings.proxies,63 )6465 # Arguments manipulation hook.66 args = dispatch_hook('args', hooks, args)6768 r = Request(**args)6970 # Pre-request hook.71 r = dispatch_hook('pre_request', hooks, r)7273 # Send the HTTP Request.74 r.send()7576 # Post-request hook.77 r = dispatch_hook('post_request', hooks, r)7879 # Response manipulation hook.80 r.response = dispatch_hook('response', hooks, r.response)8182 return r.response838485def get(url, **kwargs):8687 """Sends a GET request. Returns :class:`Response` object.8889 :param url: URL for the new :class:`Request` object.64 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.65 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.66 :param cookies: (optional) CookieJar object to send with the :class:`Request`.67 :param auth: (optional) AuthObject to enable Basic HTTP Auth.68 :param timeout: (optional) Float describing the timeout of the request.69 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.90 :param **kwargs: Optional arguments that ``request`` takes.91 """9272 return request('GET', url, **kwargs)93 return request('get', url, **kwargs)949596def head(url, **kwargs):7697 """Sends a HEAD request. Returns :class:`Response` object.9899 :param url: URL for the new :class:`Request` object.80 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.81 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.82 :param cookies: (optional) CookieJar object to send with the :class:`Request`.83 :param auth: (optional) AuthObject to enable Basic HTTP Auth.84 :param timeout: (optional) Float describing the timeout of the request.85 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.100 :param **kwargs: Optional arguments that ``request`` takes.101 """10288 return request('HEAD', url, **kwargs)103 return request('head', url, **kwargs)104105106def post(url, data='', **kwargs):92107 """Sends a POST request. Returns :class:`Response` object.108109 :param url: URL for the new :class:`Request` object.110 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.97 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.98 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.99 :param cookies: (optional) CookieJar object to send with the :class:`Request`.100 :param auth: (optional) AuthObject to enable Basic HTTP Auth.101 :param timeout: (optional) Float describing the timeout of the request.102 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.103 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.104 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.111 :param **kwargs: Optional arguments that ``request`` takes.112 """113107 return request('POST', url, data=data, **kwargs)114 return request('post', url, data=data, **kwargs)115116117def put(url, data='', **kwargs):118 """Sends a PUT request. Returns :class:`Response` object.119120 :param url: URL for the new :class:`Request` object.121 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.115 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.116 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.117 :param cookies: (optional) CookieJar object to send with the :class:`Request`.118 :param auth: (optional) AuthObject to enable Basic HTTP Auth.119 :param timeout: (optional) Float describing the timeout of the request.120 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.121 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.122 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.122 :param **kwargs: Optional arguments that ``request`` takes.123 """124125 return request('PUT', url, data=data, **kwargs)125 return request('put', url, data=data, **kwargs)126127128def patch(url, data='', **kwargs):129 """Sends a PATCH request. Returns :class:`Response` object.130131 :param url: URL for the new :class:`Request` object.132 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.133 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.134 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.135 :param cookies: (optional) CookieJar object to send with the :class:`Request`.136 :param auth: (optional) AuthObject to enable Basic HTTP Auth.137 :param timeout: (optional) Float describing the timeout of the request.138 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.139 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.140 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.133 :param **kwargs: Optional arguments that ``request`` takes.134 """135143 return request('PATCH', url, **kwargs)136 return request('patch', url, **kwargs)137138139def delete(url, **kwargs):147140 """Sends a DELETE request. Returns :class:`Response` object.141142 :param url: URL for the new :class:`Request` object.151 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.152 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.153 :param cookies: (optional) CookieJar object to send with the :class:`Request`.154 :param auth: (optional) AuthObject to enable Basic HTTP Auth.155 :param timeout: (optional) Float describing the timeout of the request.156 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.157 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.143 :param **kwargs: Optional arguments that ``request`` takes.144 """145160 return request('DELETE', url, **kwargs)146 return request('delete', url, **kwargs)
modified:requests/config.py+10 added-1 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'}60settings.accept_gzip = True61settings.proxies = None62settings.verbose = None63settings.timeout = None64settings.max_redirects = 3065settings.decode_unicode = True6667#: Use socket.setdefaulttimeout() as fallback?68settings.timeout_fallback = True
modified:requests/core.py+7 added-4 removed
10 unmodified lines
1112"""1314__title__ = 'requests'15__version__ = '0.5.1'16__build__ = 0x00050115__version__ = '0.6.1'16__build__ = 0x00060117__author__ = 'Kenneth Reitz'18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'202122from models import HTTPError, auth_manager22from models import HTTPError, Request, Response23from api import *24from exceptions import *25from sessions import session26from status_codes import codes26from config import settings27from config import settings2829import utils
modified:requests/exceptions.py+3 added
19 unmodified lines
20 """A valid URL is required to make a request."""2122class InvalidMethod(RequestException):23 """An inappropriate method was attempted."""2425class TooManyRedirects(RequestException):26 """Too many redirects."""
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+143 added-59 removed
9 unmodified lines
10import urllib211import socket12import zlib131415from urllib2 import HTTPError16from urlparse import urlparse, urlunparse, urljoin17from datetime import datetime18
1 unmodified line
20from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler21from .structures import CaseInsensitiveDict22from .packages.poster.encode import multipart_encode23from .packages.poster.streaminghttp import register_openers, get_handlers24from .utils import dict_from_cookiejar, get_unicode_from_response, decode_gzip25from .status_codes import codes23from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod26from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects272826REDIRECT_STATI = (301, 302, 303, 307)29REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)30313233class Request(object):30 """The :class:`Request <models.Request>` object. It carries out all functionality of34 """The :class:`Request <Request>` object. It carries out all functionality of35 Requests. Recommended interface is with the Requests functions.36 """3734 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH')3538 def __init__(self,39 url=None, headers=dict(), files=None, method=None, data=dict(),40 params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,41 allow_redirects=False, proxies=None):4241 socket.setdefaulttimeout(timeout)43 #: Float describ the timeout of the request.44 # (Use socket.setdefaulttimeout() as fallback)45 self.timeout = timeout4647 #: Request URL.48 self.url = url4945 #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.50 #: Dictonary of HTTP Headers to attach to the :class:`Request <Request>`.51 self.headers = headers5253 #: Dictionary of files to multipart upload (``{filename: content}``).54 self.files = files49 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.5556 #: HTTP Method to use.57 self.method = method5859 #: Dictionary or byte of request body data to attach to the52 #: :class:`Request <models.Request>`.60 #: :class:`Request <Request>`.61 self.data = None6263 #: Dictionary or byte of querystring data to attach to the55 #: :class:`Request <models.Request>`.64 #: :class:`Request <Request>`.65 self.params = None6657 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history67 #: True if :class:`Request <Request>` is part of a redirect chain (disables history68 #: and HTTPError storage).69 self.redirect = redirect7071 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)72 self.allow_redirects = allow_redirects7374 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})75 self.proxies = proxies7677 self.data, self._enc_data = self._encode_params(data)78 self.params, self._enc_params = self._encode_params(params)7968 #: :class:`Response <models.Response>` instance, containing80 #: :class:`Response <Response>` instance, containing81 #: content and metadata of HTTP Response, once :attr:`sent <send>`.82 self.response = Response()8384 if isinstance(auth, (list, tuple)):85 auth = AuthObject(*auth)86 if not auth:87 auth = auth_manager.get_auth(self.url)8876 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89 #: :class:`AuthObject` to attach to :class:`Request <Request>`.90 self.auth = auth9178 #: CookieJar to attach to :class:`Request <models.Request>`.92 #: CookieJar to attach to :class:`Request <Request>`.93 self.cookiejar = cookiejar9495 #: True if Request has been sent.96 self.sent = False9798
17 unmodified lines
116 def __repr__(self):117 return '<Request [%s]>' % (self.method)118119105 def __setattr__(self, name, value):106 if (name == 'method') and (value):107 if not value in self._METHODS:108 raise InvalidMethod()109110 object.__setattr__(self, name, value)111112120 def _checks(self):121 """Deterministic checks for consistency."""122123 if not self.url:
8 unmodified lines
132 if self.cookiejar is not None:133 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))134135 if self.auth:129 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):130 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)136 if not isinstance(self.auth.handler,137 (urllib2.AbstractBasicAuthHandler,138 urllib2.AbstractDigestAuthHandler)):139140 # TODO: REMOVE THIS COMPLETELY141 auth_manager.add_password(142 self.auth.realm, self.url,143 self.auth.username,144 self.auth.password)145146 self.auth.handler = self.auth.handler(auth_manager)147 auth_manager.add_auth(self.url, self.auth)148149 _handlers.append(self.auth.handler)
23 unmodified lines
173 return opener.open174175176 def _build_response(self, resp, is_error=False):162 """Build internal :class:`Response <models.Response>` object from given response."""177 """Build internal :class:`Response <Response>` object178 from given response.179 """180181182 def build(resp):183184 response = Response()185 response.status_code = getattr(resp, 'code', None)186187 try:188 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))171 response.read = resp.read172 response.close = resp.close189 response.fo = resp190191 if self.cookiejar:192193 response.cookies = dict_from_cookiejar(self.cookiejar)194195196 except AttributeError:197 pass198199 if is_error:
12 unmodified lines
212213 while (214 ('location' in r.headers) and215 ((self.method in ('GET', 'HEAD')) or193 (r.status_code is 303) or216 (r.status_code is codes.see_other) or217 (self.allow_redirects))218 ):219220 r.fo.close()221222 if not len(history) < settings.max_redirects:223 raise TooManyRedirects()224225 history.append(r)226227 url = r.headers['location']228229 # Handle redirection without scheme (see: RFC 1808 Section 4)230 if url.startswith('//'):231 parsed_rurl = urlparse(r.url)232 url = '%s:%s' % (parsed_rurl.scheme, url)233234 # Facilitate non-RFC2616-compliant 'location' headers235 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')203 url = urljoin(r.url, url)236 if not urlparse(url).netloc:237 url = urljoin(r.url, urllib.quote(urllib.unquote(url)))238239 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4206 if r.status_code is 303:240 if r.status_code is codes.see_other:241 method = 'GET'242 else:243 method = self.method244
20 unmodified lines
265 version of that.266267 Otherwise, assumes the data is already encoded appropriately, and268 returns it twice.235269 """270271 if hasattr(data, 'items'):272 result = []273 for k, vs in data.items():274 for v in isinstance(vs, list) and vs or [vs]:
4 unmodified lines
279 return data, data280281282 def _build_url(self):249 """Build the actual URL to use"""283 """Build the actual URL to use."""284251 # Support for unicode domain names.252 parsed_url = list(urlparse(self.url))253 parsed_url[1] = parsed_url[1].encode('idna')254 self.url = urlunparse(parsed_url)285 # Support for unicode domain names and paths.286 scheme, netloc, path, params, query, fragment = urlparse(self.url)287 netloc = netloc.encode('idna')288 if isinstance(path, unicode):289 path = path.encode('utf-8')290 path = urllib.quote(urllib.unquote(path))291 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))292293 if self._enc_params:294 if urlparse(self.url).query:295 return '%s&%s' % (self.url, self._enc_params)
12 unmodified lines
308309 :param anyway: If True, request will be sent, even if it has310 already been sent.311 """312313 self._checks()314 success = False315316 # Logging
20 unmodified lines
337 else:338 req = _Request(url, data=self._enc_data, method=self.method)339340 if self.headers:303 req.headers.update(self.headers)341 for k,v in self.headers.iteritems():342 req.add_header(k, v)343344 if not self.sent or anyway:345346 try:347 opener = self._get_opener()309 resp = opener(req)348 try:349350 resp = opener(req, timeout=self.timeout)351352 except TypeError, err:353 # timeout argument is new since Python v2.6354 if not 'timeout' in str(err):355 raise356357 if settings.timeout_fallback:358 # fall-back and use global socket timeout (This is not thread-safe!)359 old_timeout = socket.getdefaulttimeout()360 socket.setdefaulttimeout(self.timeout)361362 resp = opener(req)363364 if settings.timeout_fallback:365 # restore gobal timeout366 socket.setdefaulttimeout(old_timeout)367368 if self.cookiejar is not None:369 self.cookiejar.extract_cookies(resp, req)370371 except (urllib2.HTTPError, urllib2.URLError), why:
2 unmodified lines
374 why = Timeout(why)375376 self._build_response(why, is_error=True)377321378 else:379 self._build_response(resp)380 self.response.ok = True381
38 unmodified lines
420421 #: Params handled in _build_url422 return curl_cmd + method_opt + data + header + '"' + self._build_url() + '"'423368424class Response(object):370 """The core :class:`Response <models.Response>` object. All371 :class:`Request <models.Request>` objects contain a372 :class:`response <models.Response>` attribute, which is an instance425 """The core :class:`Response <Response>` object. All426 :class:`Request <Request>` objects contain a427 :class:`response <Response>` attribute, which is an instance428 of this class.429 """430431 def __init__(self):377 #: Raw content of the response, in bytes.378 #: If ``content-encoding`` of response was set to ``gzip``, the379 #: response data will be automatically deflated.432433 self._content = None434435 #: Integer Code of responded HTTP Status.436 self.status_code = None437438 #: Case-insensitive Dictionary of Response Headers.439 #: For example, ``headers['content-encoding']`` will return the440 #: value of a ``'Content-Encoding'`` response header.441 self.headers = CaseInsensitiveDict()442443 #: File-like object representation of response (for advanced usage).444 self.fo = None445446 #: Final URL location of Response.447 self.url = None448449 #: True if no :attr:`error` occured.450 self.ok = False451452 #: Resulting :class:`HTTPError` of request, if one occured.453 self.error = None454393 #: A list of :class:`Response <models.Response>` objects from455 #: A list of :class:`Response <Response>` objects from456 #: the history of the Request. Any redirect responses will end457 #: up here.458 self.history = []459397 #: The Request that created the Response.460 #: The :class:`Request <Request>` that created the Response.461 self.request = None462463 #: A dictionary of Cookies the server sent back.464 self.cookies = None465466467 def __repr__(self):468 return '<Response [%s]>' % (self.status_code)469470471 def __nonzero__(self):472 """Returns true if :attr:`status_code` is 'OK'."""473474 return not self.error475476410 def __getattr__(self, name):411 """Read and returns the full stream when accessing to :attr: `content`"""412 if name == 'content':413 if self._content is not None:414 return self._content415 self._content = self.read()416 if self.headers.get('content-encoding', '') == 'gzip':417 try:418 self._content = zlib.decompress(self._content, 16+zlib.MAX_WBITS)419 except zlib.error:420 pass477 @property478 def content(self):479 """Content of the response, in bytes or unicode480 (if available).481 """482483 if self._content is not None:484 return self._content485486 # Read the contents.487 self._content = self.fo.read()488489 # Decode GZip'd content.490 if 'gzip' in self.headers.get('content-encoding', ''):491 try:492 self._content = decode_gzip(self._content)493 except zlib.error:494 pass495496 # Decode unicode content.497 if settings.decode_unicode:498 self._content = get_unicode_from_response(self)499500 return self._content501502503 def raise_for_status(self):504 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""505 if self.error:506 raise self.error507508509510class AuthManager(object):511 """Requests Authentication Manager."""512513 def __new__(cls):
65 unmodified lines
579580581 def reduce_uri(self, uri, default_port=True):582 """Accept authority or URI and extract only the authority and path."""583584 # note HTTP URLs do not have a userinfo component585 parts = urllib2.urlparse.urlsplit(uri)586587 if parts[1]:588 # URI589 scheme = parts[0]590 authority = parts[1]
2 unmodified lines
593 # host or host:port594 scheme = None595 authority = uri596 path = '/'597598 host, port = urllib2.splitport(authority)599600 if default_port and port is None and scheme is not None:601 dport = {"http": 80,602 "https": 443,603 }.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)
modified:requests/status_codes.py+4 added-4 removed
20 unmodified lines
21 208: ('im_used',),2223 # Redirection.24 300: ('multiple_choices',),25 301: ('moved_pemanently', 'moved'),25 301: ('moved_permanently', 'moved', '\\o-'),26 302: ('found',),27 302: ('see_other', 'other'),27 303: ('see_other', 'other'),28 304: ('not_modified',),29 305: ('use_proxy',),30 306: ('switch_proxy',),31 307: ('temporary_redirect', 'temporary_moved', 'temporary'),
3 unmodified lines
35 400: ('bad_request', 'bad'),36 401: ('unauthorized',),37 402: ('payment_required', 'payment'),38 403: ('forbidden',),39 404: ('not_found',),39 404: ('not_found', '-o-'),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'),
17 unmodified lines
61 450: ('blocked_by_windows_parental_controls', 'parental_controls'),62 499: ('client_closed_request',),6364 # Server Error.65 500: ('iternal_server_error', 'server_error'),65 500: ('internal_server_error', 'server_error', '/o\\'),66 501: ('not_implemented',),67 502: ('bad_gateway',),68 503: ('service_unavailable', 'unavailable'),69 504: ('gateway_timeout',),
14 unmodified lines
added:requests/utils.py+165 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 cgi13import cookielib14import re15import zlib161718def dict_from_cookiejar(cj):19 """Returns a key/value dictionary from a CookieJar.2021 :param cj: CookieJar object to extract cookies from.22 """2324 cookie_dict = {}2526 for _, cookies in cj._cookies.items():27 for _, cookies in cookies.items():28 for cookie in cookies.values():29 # print cookie30 cookie_dict[cookie.name] = cookie.value3132 return cookie_dict333435def cookiejar_from_dict(cookie_dict):36 """Returns a CookieJar from a key/value dictionary.3738 :param cookie_dict: Dict of key/values to insert into CookieJar.39 """4041 # return cookiejar if one was passed in42 if isinstance(cookie_dict, cookielib.CookieJar):43 return cookie_dict4445 # create cookiejar46 cj = cookielib.CookieJar()4748 cj = add_dict_to_cookiejar(cj, cookie_dict)4950 return cj515253def add_dict_to_cookiejar(cj, cookie_dict):54 """Returns a CookieJar from a key/value dictionary.5556 :param cj: CookieJar to insert cookies into.57 :param cookie_dict: Dict of key/values to insert into CookieJar.58 """5960 for k, v in cookie_dict.items():6162 cookie = cookielib.Cookie(63 version=0,64 name=k,65 value=v,66 port=None,67 port_specified=False,68 domain='',69 domain_specified=False,70 domain_initial_dot=False,71 path='/',72 path_specified=True,73 secure=False,74 expires=None,75 discard=True,76 comment=None,77 comment_url=None,78 rest={'HttpOnly': None},79 rfc2109=False80 )8182 # add cookie to cookiejar83 cj.set_cookie(cookie)8485 return cj868788def get_encodings_from_content(content):89 """Returns encodings from given content string.9091 :param content: bytestring to extract encodings from.92 """9394 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)9596 return charset_re.findall(content)979899100def get_encoding_from_headers(headers):101 """Returns encodings from given HTTP Header Dict.102103 :param headers: dictionary to extract encoding from.104 """105106 content_type = headers.get('content-type')107 content_type, params = cgi.parse_header(content_type)108109 if 'charset' in params:110 return params['charset'].strip("'\"")111112113def get_unicode_from_response(r):114 """Returns the requested content back in unicode.115116 :param r: Reponse object to get unicode content from.117118 Tried:119120 1. charset from content-type121122 2. every encodings from ``<meta ... charset=XXX>``123124 3. fall back and replace all unicode characters125126 """127128 tried_encodings = []129130 # Try charset from content-type131 encoding = get_encoding_from_headers(r.headers)132133 if encoding:134 try:135 print '!'136 return unicode(r.content, encoding)137 except UnicodeError:138 tried_encodings.append(encoding)139140 # Try every encodings from <meta ... charset=XXX>141 encodings = get_encodings_from_content(r.content)142143 for encoding in encodings:144 if encoding in tried_encodings:145 continue146 try:147148 return unicode(r.content, encoding)149 except (UnicodeError, TypeError):150 tried_encodings.append(encoding)151152 # Fall back:153 try:154 return unicode(r.content, encoding, errors='replace')155 except TypeError:156 return r.content157158159def decode_gzip(content):160 """Return gzip-decoded string.161162 :param content: bytestring to gzip-decode.163 """164165 return zlib.decompress(content, 16+zlib.MAX_WBITS)
modified:AUTHORS+10 added-1 removed
29 unmodified lines
30- 潘旭 (Xu Pan)31- Tamás Gulácsi32- Rubén Abad33- Peter Manser34- Jeremy Selie34- Jeremy Selier35- Jens Diemer36- Alex <@alopatin>37- Tom Hogans <tomhsx@gmail.com>38- Armin Ronacher39- Shrikant Sharat Kandula40- Mikko Ohtamaa41- Den Shabalin42- Alejandro Giacometti43- Rick Mak
modified:HISTORY.rst+23 added-3 removed
1History2-------340.5.2 (2011-09-??)4* Automatic decoding of unicode, when available.5* New ``decode_unicode`` setting6* Removal of ``r.read/close`` methods7* New ``r.fo`` interface for advanced response usage.89100.6.1 (2011-08-20)11++++++++++++++++++127* status code reference dict?13* Enhanced status codes experience ``\o/``14* Set a maximum number of redirects (``settings.max_redirects``)15* Full Unicode URL support16* Support for protocol-less redirects.17* Allow for arbitrary request types.18* Bugfixes1920210.6.0 (2011-08-17)22++++++++++++++++++2324* New callback hook system25* New persistient sessions object and context manager26* Transparent Dict-cookie handling27* Status code reference object28* Removed Response.cached29* Added Response.request10* all args are kwargs30* All args are kwargs31* Relative redirect support32* HTTPError handling improvements33* Improved https testing34* Bugfixes
132 unmodified lines
modified:MANIFEST.in+1 added-1 removed
1include README.rst LICENSE HISTORY.rst 1include README.rst LICENSE HISTORY.rst test_requests.py
modified:README.rst+27 added-83 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
40 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.patch(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: ::
13 unmodified lines
99100If you'd like to contribute, simply fork `the repository`_, commit your changes to the **develop** branch (or branch off of it), and send a pull request. Make sure you add yourself to AUTHORS_.101102153154Roadmap155-------156157- Sphinx Documentation158103.. _`the repository`: http://github.com/kennethreitz/requests104.. _AUTHORS: http://github.com/kennethreitz/requests/blob/master/AUTHORS
modified:test_requests.py+36 added-20 removed
11 unmodified lines
12 import json1314import requests1516from requests.sessions import Session171819HTTPBIN_URL = 'http://httpbin.org/'20HTTPSBIN_URL = 'https://httpbin.ep.io/'
110 unmodified lines
131 r = requests.patch(httpsbin('patch'))132 self.assertEqual(r.status_code, 200)133134134 def test_AUTH_HTTPS_200_OK_GET(self):135 def test_AUTH_HTTP_200_OK_GET(self):136137 for service in SERVICES:138139 auth = ('user', 'pass')140 url = service('basic-auth', 'user', 'pass')140 r = requests.get(url, auth=auth)141142 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)149147 # reset auto authentication148 requests.auth_manager.empty()150150151 def test_POSTBIN_GET_POST_FILES(self):152153 for service in SERVICES:154
88 unmodified lines
243 r = requests.get(httpbin('gzip'))244 r.content.decode('ascii')245246247 def test_autoauth(self):248249 http_auth = ('user', 'pass')250 requests.auth_manager.add_auth('httpbin.org', http_auth)251252 r = requests.get(httpbin('basic-auth', 'user', 'pass'))253 self.assertEquals(r.status_code, 200)254255256 requests.auth_manager.add_auth('httpbin.ep.io', http_auth)257258 r = requests.get(httpsbin('basic-auth', 'user', 'pass'))259 self.assertEquals(r.status_code, 200)260261247 def test_unicode_get(self):248249 for service in SERVICES:250
188 unmodified lines
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()