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
Provenance
- Commit
68a2954- Tree
052a67d- Author
Mike Waldner <mwaldner@gilt.com>- Committer
Mike Waldner <mwaldner@gilt.com>- Parent 1
c56acf0- Parent 2
75027f9
25 files changed+1066 added−314 removed
added:docs/community/faq.rst+67 added
1+.. _faq:2+3+Frequently Asked Questions4+==========================5+6+This part of the documentation answers common questions about Requests.7+8+Encoded Data?9+-------------10+11+Requests automatically decompresses gzip-encoded responses, and does12+it's best to decodes response content to unicode when possible.13+14+You can get direct access to the raw response (and even the socket),15+if needed as well.16+17+18+Custom User-Agents?19+-------------------20+21+Requests allows you to easily override User-Agent strings, along with22+any other HTTP Header.23+24+25+Why not Httplib2?26+-----------------27+28+Chris Adams gave an excellent summary on29+`Hacker News <http://news.ycombinator.com/item?id=2884406>`_:30+31+ 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].39+40+ Disclosure: I'm listed in the requests AUTHORS file but can claim credit41+ for, oh, about 0.0001% of the awesomeness.42+43+ 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.49+50+51+Python 3 Support?52+-----------------53+54+It's on the way. Here's a list of `supported interpreters <interpreters>`_.55+56+57+Keep-alive Support?58+-------------------59+60+It's on the way.61+62+63+Proxy Support?64+--------------65+66+You bet!67+added:docs/community/support.rst+37 added
1+.. _support:2+3+Support4+=======5+6+If you have a questions or issues about Requests, there are serveral options:7+8+Send a Tweet9+------------10+11+If your question is less than 140 characters, feel free to send a tweet to12+`@kennethreitz <http://twitter.com/kennethreitz>`_.13+14+15+File an Issue16+-------------17+18+If you notice some unexpected behavior in Requests, or want to see support19+for a new feature,20+`file an issue on GitHub <https://github.com/kennethreitz/requests/issues>`_.21+22+23+E-mail24+------25+26+I'm more than happy to answer any personal or in-depth questions about27+Requests. Feel free to email28+`requests@kennethreitz.com <mailto:requests@kennethreitz.com>`_.29+30+31+IRC32+---33+34+The official Freenode channel for Requests is35+`#python-requests <irc://irc.freenode.net/python-requests>`_36+37+I'm also available as **kennethreitz** on Freenode.added:docs/community/updates.rst+30 added
1+.. _updates:2+3+Updates4+=======5+6+If you'd like to stay up to date on the community and development of Requests,7+there are serveral options:8+9+GitHub10+------11+12+The best way to track the development of Requests is through13+`the GitHub repo <https://github.com/kennethreitz/requests>`_.14+15+Twitter16+-------17+18+I often tweet about new features and releases of Requests.19+20+Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.21+22+23+Mailing List24+------------25+26+There's a low-volume mailing list for Requests. To subscribe to the27+mailing list, send an email to28+`requests@librelist.org <mailto:requests@librelist.org>`_.29+30+added:docs/dev/authors.rst+5 added
1+Authors2+=======3+4+5+.. include:: ../../AUTHORSmodified:docs/user/advanced.rst+137 added
1+.. _advanced:2+3+Advanced Usage4+==============5+6+This document covers some of Requests more advanced features.7+8+9+Session Objects10+---------------11+12+The Session object allows you to persist certain parameters across13+requests. It also establishes a CookieJar and passes it along14+to any requests made from the Session instance.15+16+A session object has all the methods of the main Requests API.17+18+Let's persist some cookies across requests::19+20+ with requests.session() as s:21+22+ s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23+ r = s.get("http://httpbin.org/cookies")24+25+ print r.content26+ # '{"cookies": {"sessioncookie": "123456789"}}'27+28+29+Sessions can also be used to provide default data to the request methods::30+31+ headers = {'x-test': 'true'}32+ auth = ('user', 'pass')33+34+ with requests.session(auth=auth, headers=headers) as c:35+36+ # both 'x-test' and 'x-test2' are sent37+ c.get('http://httpbin.org/headers', headers={'x-test2': 'true'})38+39+40+.. admonition:: Global Settings41+42+ Certain parameters are best set at the ``request.config`` level43+ (e.g.. a global proxy, user agent header).44+45+46+Event Hooks47+-----------48+49+Requests has a hook system that you can use to manipulate portions of50+the request process, or signal event handling.51+52+Available hooks:53+54+``args``:55+ A dictionary of the arguments being sent to Request().56+57+``pre_request``:58+ The Request object, directly before being sent.59+60+``post_request``:61+ The Request object, directly after being sent.62+63+``response``:64+ The response generated from a Request.65+66+67+You can assign a hook function on a per-request basis by passing a68+``{hook_name: callback_function}`` dictionary to the ``hooks`` request69+parameter::70+71+ hooks=dict(args=print_url)72+73+That ``callback_function`` will receive a chunk of data as its first74+argument.75+76+::77+78+ def print_url(args):79+ print args['url']80+81+If an error occurs while executing your callback, a warning is given.82+83+If the callback function returns a value, it is assumed that it is to84+replace the data that was passed in. If the function doesn't return85+anything, nothing else is effected.86+87+Let's print some request method arguments at runtime::88+89+ >>> requests.get('http://httpbin', hooks=dict(args=print_url))90+ http://httpbin91+ <Response [200]>92+93+Let's hijack some arguments this time with a new callback::94+95+ def hack_headers(args):96+ if not args[headers]:97+ args['headers'] = dict()98+99+ args['headers'].update({'X-Testing': 'True'})100+101+ return args102+103+ hooks = dict(args=hack_headers)104+ headers = dict(yo=dawg)105+106+And give it a try::107+108+ >>> requests.get('http://httpbin/headers', hooks=hooks, headers=headers)109+ {110+ "headers": {111+ "Content-Length": "",112+ "Accept-Encoding": "gzip",113+ "Yo": "dawg",114+ "X-Forwarded-For": "::ffff:24.127.96.129",115+ "Connection": "close",116+ "User-Agent": "python-requests.org",117+ "Host": "httpbin.org",118+ "X-Testing": "True",119+ "X-Forwarded-Protocol": "",120+ "Content-Type": ""121+ }122+ }123+124+125+126+Verbose Logging127+---------------128+129+If you want to get a good look at what HTTP requests are being sent130+by your application, you can turn on verbose logging.131+132+To do so, just configure Requests with a stream to write to::133+134+ >>> requests.settings.verbose = sys.stderr135+ >>> requests.get('http://httpbin.org/headers')136+ 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers137+ <Response [200]>modified:docs/user/install.rst+6 added-3 removed
1 unmodified line2 3 Installation4 ============5 6-This part of the documentation covers the installation of Requests. The first step to using any software package is getting it properly installed.6+This part of the documentation covers the installation of Requests.7+The first step to using any software package is getting it properly installed.8 9 10 Distribute & Pip11 ----------------12 unmodified lines24 25 Cheeseshop Mirror26 -----------------27 27-If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::28+If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's29+personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::30 31 $ pip install -i http://pip.kreitz.co/simple requests32 33 15 unmodified lines49 50 $ curl -O https://github.com/kennethreitz/requests/zipball/master51 52 51-Once you have a copy of the source, you can embed it in your Python package, or install it into your site-packages easily::53+Once you have a copy of the source, you can embed it in your Python package,54+or install it into your site-packages easily::55 56 $ python setup.py installmodified:docs/user/intro.rst+18 added-3 removed
1+.. _introduction:2+3 Introduction4 ============5 6 Philosophy13 unmodified lines20 21 ISC License22 -----------23 24+A large number of open source projects you find today are `GPL Licensed`_.25+While the GPL has its time and place, it should most certainly not be your26+go-to license for your next open source project.27 23-A 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.28+A project that is released as GPL cannot be used in any commercial product29+without the product itself also being offered as open source.30 25-A 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.31+The MIT, BSD, ISC, and Apache2 licenses are great alternatives to the GPL32+that allow your open-source software to be used freely in proprietary,33+closed-source software.34 35 Requests is released under terms of `The ISC License`_.36 37 .. _`GPL Licensed`: http://www.opensource.org/licenses/gpl-license.php9 unmodified lines47 48 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.49 50 51+.. _interpreters:52 Python Interpreters53 -------------------54 55 At this time, the following Python platforms are officially supported:56 57 * 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.568 69 55-Support for Python 3.x is planned.70+Support for Python 3.x is planned.modified:docs/user/quickstart.rst+102 added-48 removed
1-Feature Overview2-================1+.. _quickstart:2 4-Requests is designed to solve a 90% use case — making simple requests. While most5-HTTP libraries are extremely extensible, they often attempt to support the entire HTTP Spec.6-This often leads to extremely messy and cumbersome APIs, as is the case with urllib2. Requests abandons support for edge-cases, and focuses on the essentials.3+Quickstart4+==========5 6+.. module:: requests.models7 9-.. _features:8+Eager to get started? This page gives a good introduction in how to get started9+with Requests. This assumes you already have Requests installed. If you do not,10+head over to the :ref:`Installation <install>` section.11 11-Requests Can:12--------------12+First, make sure that:13 14-- Make **GET**, **POST**, **PUT**, **DELETE**, and **HEAD** requests.15-- Handle HTTP and HTTPS Requests16-- Add Request headers (with a simple dictionary)17-- URLEncode your Form Data (with a simple dictionary)18-- Add Multi-part File Uploads (with a simple dictionary)19-- Handle CookieJars (with a single parameter)20-- Add HTTP Authentication (with a single parameter)21-- Handle redirects (with history)22-- Automatically decompress GZip'd responses23-- Support Unicode URLs24-- Gracefully timeout25-- Interface with Eventlet & Gevent14+* Requests is :ref:`installed <install>`15+* Requests is :ref:`up-to-date <updates>`16 17 28-Requests Can't:29----------------18+Lets gets started with some simple use cases and examples.19 31-- Handle Caching32-- Handle Keep-Alives20 21+Make a GET Request22+------------------23 35-Quickstart36-==========24+Making a standard request with Requests is very simple.25 26+Let's get GitHub's public timeline ::27 39-GET Request40------------28+ r = requests.get('https://github.com/timeline.json')29 30+Now, we have a :class:`Response` object called ``r``. We can get all the31+information we need from this.32 43-Adding Parameters44------------------33 34+Response Content35+----------------36 37+We can read the content of the server's response::38 48-Adding Headers49---------------39+ >>> r.content40+ '[{"repository":{"open_issues":0,"url":"https://github.com/...41 42 43+Response Status Codes44+---------------------45 53-HTTP Basic Auth54----------------46+We can check the response status code::47 48+ >>> r.status_code49+ 20050 57-Tracking Redirects58-------------------51+Requests also comes with a built-in status code lookup object for easy52+reference::53 54+ >>> r.status_code == requests.codes.ok55+ True56 57+If we made a bad request, we can raise it with58+:class:`Response.raise_for_status()`::59 60+ >>> _r = requests.get('http://httpbin.org/status/404')61+ >>> _r.status_code62+ 40463 63-HTTP 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 FOUND69 70+But, since our ``status_code`` was ``200``, when we call it::71 67-HTTP POST (Binary Data)68------------------------72+ >>> r.raise_for_status()73+ None74 75+All is well.76 71-HTTP POST (Multipart Files)72----------------------------77 78+Response Headers79+----------------80 75-HTTP PUT76---------81+We can view the server's response headers with a simple Python dictionary82+interface::83 84+ >>> 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+ }95 79-HTTP DELETE80------------96+The dictionary is special, though: it's made just for HTTP headers. According to97+`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP98+Headers are case-insensitive.99 100+So, we can access the headers using any capitalization we want::101 83-HTTP HEAD84----------102+ >>> r.headers['Content-Type']103+ 'application/json; charset=utf-8'104+105+ >>> r.headers.get('content-type')106+ 'application/json; charset=utf-8'107+108+If a header doesn't exist in the Response, its value defaults to ``None``::109+110+ >>> r.headers['X-Random']111+ None112+113+114+Cookies115+-------116+117+If a response contains some Cookies, you can get quick access to them::118+119+ >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'120+ >>> r = requests.get(url)121+122+ >>> print r.cookies123+ {'requests-is': 'awesome'}124+125+The underlying CookieJar is also available for more advanced handling::126+127+ >>> r.request.cookiejar128+ <cookielib.CookieJar>129+130+To send your own cookies to the server, you can use the ``cookies``131+parameter::132+133+ >>> url = 'http://httpbin.org/cookies'134+ >>> cookies = dict(cookies_are='working')135+136+ >>> r = requests.get(url, cookies=cookies)137+ >>> r.content138+ '{"cookies": {"cookies_are": "working"}}'modified:docs/api.rst+39 added-18 removed
11 unmodified lines12 13 Main Interface14 --------------15 16-All of Request's functionality can be accessed by these 6 methods. They17-all return a :class:`Response <models.Response>` object.16+All of Request's functionality can be accessed by these 7 methods.17+They all return an instance of the :class:`Response <Response>` object.18 19+.. autofunction:: request20 .. autofunction:: head21 .. autofunction:: get22 .. autofunction:: post23 .. autofunction:: put3 unmodified lines27 28 -----------29 30 30-.. autoclass:: requests.models.Response31+.. autoclass:: Response32 :inherited-members:33 34 34-Exceptions35-----------35 37-.. autoexception:: HTTPError36+Utilities37+---------38 39-.. autoexception:: RequestException39+These functions are used internally, but may be useful outside of40+Requests.41 41-.. autoexception:: requests.models.AuthenticationError42-.. autoexception:: requests.models.URLRequired43-.. autoexception:: requests.models.InvalidMethod42+.. module:: requests.utils43 44+Cookies45+~~~~~~~46 47+.. autofunction:: dict_from_cookiejar48+.. autofunction:: cookiejar_from_dict49+.. autofunction:: add_dict_to_cookiejar50+51+Encodings52+~~~~~~~~~53+54+.. autofunction:: get_encodings_from_content55+.. autofunction:: get_encoding_from_headers56+.. autofunction:: get_unicode_from_response57+.. autofunction:: decode_gzip58+59+60 Internals61 ---------62 63 These items are an internal component to Requests, and should never be64 seen by the end user (developer). This part of the API documentation65 exists for those who are extending the functionality of Requests.66 53-Functions54-~~~~~~~~~67+Exceptions68+~~~~~~~~~~69 56-.. autofunction:: request70+.. module:: requests71 72+.. autoexception:: HTTPError73+74+.. autoexception:: RequestException75+76+.. autoexception:: AuthenticationError77+.. autoexception:: URLRequired78+.. autoexception:: InvalidMethod79+.. autoexception:: TooManyRedirects80+81+82+83 Classes84 ~~~~~~~85 61-.. autoclass:: requests.models.Request86+.. autoclass:: requests.Request87 :inherited-members:88 64-Structures65-~~~~~~~~~~89 67-.. autoclass:: requests.structures.CaseInsensitiveDict68- :inherited-members:modified:docs/conf.py+1 added-1 removed
153 unmodified lines154 # If true, the index is split into individual pages for each letter.155 #html_split_index = False156 157 # If true, links to the reST sources are added to the pages.158-html_show_sourcelink = True158+html_show_sourcelink = False159 160 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.161 html_show_sphinx = False162 82 unmodified linesmodified:docs/index.rst+26 added-6 removed
11 unmodified lines12 13 Most existing Python modules for sending HTTP requests are extremely verbose14 and cumbersome. Python's builtin **urllib2** module provides most of15 the HTTP capabilities you should need, but the api is thoroughly **broken**.16-It requires an *enormous* amount of work (even method overrides) to perform the simplest of tasks.16+It requires an *enormous* amount of work (even method overrides) to perform17+the simplest of tasks.18 19 Things shouldn’t be this way. Not in Python.20 21 ::19 unmodified lines41 42 `Twitter, Inc <http://twitter.com>`_ uses Requests internally.43 44 **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.47 48 **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.51 52 **Rich Leland**53 Requests is awesome. That is all.54 55 **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!58 59 60 User Guide61 ----------62 59-This part of the documentation, which is mostly prose, begins with some background information about Requests, then focuses on step-by-step instructions for getting the most out of Requests.63+This part of the documentation, which is mostly prose, begins with some64+background information about Requests, then focuses on step-by-step65+instructions for getting the most out of Requests.66 67 .. toctree::68 :maxdepth: 269 70 user/intro71 user/install66-.. user/quickstart72+ user/quickstart73 user/advanced74 75 76+Community Guide77+-----------------78+79+This part of the documentation, which is mostly prose, details the80+Requests ecosystem and community.81+82+.. toctree::83+ :maxdepth: 284+85+ community/faq86+ community/support87+ community/updates88+89 API Documentation90 -----------------91 92 If you are looking for information on a specific function, class or method,15 unmodified lines108 :maxdepth: 2109 110 dev/internals111 dev/todo112+ dev/authorsmodified:requests/api.py+45 added-59 removed
10 unmodified lines11 12 """13 14 import config15-from .models import Request, Response, AuthManager, AuthObject, auth_manager15+from .models import Request, Response, AuthObject16 from .status_codes import codes17+from .hooks import dispatch_hook18+from .utils import cookiejar_from_dict19 20+from urlparse import urlparse21 22 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')23 24 def request(method, url,25 params=None, data=None, headers=None, cookies=None, files=None, auth=None,23- timeout=None, allow_redirects=False, proxies=None):26+ timeout=None, allow_redirects=False, proxies=None, hooks=None):27 25- """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.30 31 :param method: method for the new :class:`Request` object.32 :param url: URL for the new :class:`Request` object.33 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.34 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.35 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.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 """43 40- r = Request(44+ method = str(method).upper()45+46+ if cookies is None:47+ cookies = {}48+49+ cookies = cookiejar_from_dict(cookies)50+51+ 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 )64 65+ # Arguments manipulation hook.66+ args = dispatch_hook('args', hooks, args)67+68+ r = Request(**args)69+70+ # Pre-request hook.71+ r = dispatch_hook('pre_request', hooks, r)72+73+ # Send the HTTP Request.74 r.send()75 76+ # Post-request hook.77+ r = dispatch_hook('post_request', hooks, r)78+79+ # Response manipulation hook.80+ r.response = dispatch_hook('response', hooks, r.response)81+82 return r.response83 84 85 def get(url, **kwargs):86 87 """Sends a GET request. Returns :class:`Response` object.88 89 :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 """92 72- return request('GET', url, **kwargs)93+ return request('get', url, **kwargs)94 95 96 def head(url, **kwargs):76-97 """Sends a HEAD request. Returns :class:`Response` object.98 99 :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 """102 88- return request('HEAD', url, **kwargs)103+ return request('head', url, **kwargs)104 105 106 def post(url, data='', **kwargs):92-107 """Sends a POST request. Returns :class:`Response` object.108 109 :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 """113 107- return request('POST', url, data=data, **kwargs)114+ return request('post', url, data=data, **kwargs)115 116 117 def put(url, data='', **kwargs):118 """Sends a PUT request. Returns :class:`Response` object.119 120 :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 """124 125- return request('PUT', url, data=data, **kwargs)125+ return request('put', url, data=data, **kwargs)126 127 128 def patch(url, data='', **kwargs):129 """Sends a PATCH request. Returns :class:`Response` object.130 131 :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 """135 143- return request('PATCH', url, **kwargs)136+ return request('patch', url, **kwargs)137 138 139 def delete(url, **kwargs):147-140 """Sends a DELETE request. Returns :class:`Response` object.141 142 :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 """145 160- return request('DELETE', url, **kwargs)146+ return request('delete', url, **kwargs)modified:requests/config.py+10 added-1 removed
10 unmodified lines11 class Settings(object):12 _singleton = {}13 14 # attributes with defaults15- __attrs__ = ('timeout', 'verbose')15+ __attrs__ = []16 17 def __init__(self, **kwargs):18 super(Settings, self).__init__()19 32 unmodified lines52 except AttributeError:53 return None54 return object.__getattribute__(self, key)55 56+57 settings = Settings()58+59 settings.base_headers = {'User-Agent': 'python-requests.org'}60 settings.accept_gzip = True61 settings.proxies = None62+settings.verbose = None63+settings.timeout = None64+settings.max_redirects = 3065+settings.decode_unicode = True66+67+#: Use socket.setdefaulttimeout() as fallback?68+settings.timeout_fallback = Truemodified:requests/core.py+7 added-4 removed
10 unmodified lines11 12 """13 14 __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'20 21 22-from models import HTTPError, auth_manager22+from models import HTTPError, Request, Response23 from api import *24 from exceptions import *25+from sessions import session26 from status_codes import codes26-from config import settings27+from config import settings28+29+import utilsmodified:requests/exceptions.py+3 added
19 unmodified lines20 """A valid URL is required to make a request."""21 22 class InvalidMethod(RequestException):23 """An inappropriate method was attempted."""24+25+class TooManyRedirects(RequestException):26+ """Too many redirects."""added:requests/hooks.py+40 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.hooks5+~~~~~~~~~~~~~~6+7+This module provides the capabilities for the Requests hooks system.8+9+Available hooks:10+11+``args``:12+ A dictionary of the arguments being sent to Request().13+14+``pre_request``:15+ The Request object, directly before being sent.16+17+``post_request``:18+ The Request object, directly after being sent.19+20+``response``:21+ The response generated from a Request.22+23+"""24+25+import warnings26+27+28+def dispatch_hook(key, hooks, hook_data):29+ """Dipatches a hook dictionary on a given peice of data."""30+31+ hooks = hooks or dict()32+33+ if key in hooks:34+ try:35+ return hooks.get(key).__call__(hook_data) or hook_data36+37+ except Exception, why:38+ warnings.warn(str(why))39+40+ return hook_datamodified:requests/models.py+143 added-59 removed
9 unmodified lines10 import urllib211 import socket12 import zlib13 14+15 from urllib2 import HTTPError16 from urlparse import urlparse, urlunparse, urljoin17 from datetime import datetime18 1 unmodified line20 from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler21 from .structures import CaseInsensitiveDict22 from .packages.poster.encode import multipart_encode23 from .packages.poster.streaminghttp import register_openers, get_handlers24+from .utils import dict_from_cookiejar, get_unicode_from_response, decode_gzip25+from .status_codes import codes23-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod26+from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects27 28 26-REDIRECT_STATI = (301, 302, 303, 307)29+REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)30 31 32+33 class 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 """37 34- _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH')35-38 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):42 41- socket.setdefaulttimeout(timeout)43+ #: Float describ the timeout of the request.44+ # (Use socket.setdefaulttimeout() as fallback)45+ self.timeout = timeout46 47 #: Request URL.48 self.url = url49+45- #: 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 = headers52+53 #: Dictionary of files to multipart upload (``{filename: content}``).54 self.files = files49- #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.55+56+ #: HTTP Method to use.57 self.method = method58+59 #: Dictionary or byte of request body data to attach to the52- #: :class:`Request <models.Request>`.60+ #: :class:`Request <Request>`.61 self.data = None62+63 #: Dictionary or byte of querystring data to attach to the55- #: :class:`Request <models.Request>`.64+ #: :class:`Request <Request>`.65 self.params = None66+57- #: 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 = redirect70+71 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)72 self.allow_redirects = allow_redirects73+74 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})75 self.proxies = proxies76 77 self.data, self._enc_data = self._encode_params(data)78 self.params, self._enc_params = self._encode_params(params)79 68- #: :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()83 84 if isinstance(auth, (list, tuple)):85 auth = AuthObject(*auth)86 if not auth:87 auth = auth_manager.get_auth(self.url)88+76- #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89+ #: :class:`AuthObject` to attach to :class:`Request <Request>`.90 self.auth = auth91+78- #: CookieJar to attach to :class:`Request <models.Request>`.92+ #: CookieJar to attach to :class:`Request <Request>`.93 self.cookiejar = cookiejar94+95 #: True if Request has been sent.96 self.sent = False97 98 17 unmodified lines116 def __repr__(self):117 return '<Request [%s]>' % (self.method)118 119 105- def __setattr__(self, name, value):106- if (name == 'method') and (value):107- if not value in self._METHODS:108- raise InvalidMethod()109-110- object.__setattr__(self, name, value)111-112-120 def _checks(self):121 """Deterministic checks for consistency."""122 123 if not self.url:8 unmodified lines132 if self.cookiejar is not None:133 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))134 135 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)):139+140+ # TODO: REMOVE THIS COMPLETELY141+ auth_manager.add_password(142+ self.auth.realm, self.url,143+ self.auth.username,144+ self.auth.password)145+146 self.auth.handler = self.auth.handler(auth_manager)147 auth_manager.add_auth(self.url, self.auth)148 149 _handlers.append(self.auth.handler)23 unmodified lines173 return opener.open174 175 176 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+ """180 181+182 def build(resp):183 184 response = Response()185 response.status_code = getattr(resp, 'code', None)186 187 try:188 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))171- response.read = resp.read172- response.close = resp.close189+ response.fo = resp190+191+ if self.cookiejar:192+193+ response.cookies = dict_from_cookiejar(self.cookiejar)194+195+196 except AttributeError:197 pass198 199 if is_error:12 unmodified lines212 213 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 ):219 220+ r.fo.close()221+222+ if not len(history) < settings.max_redirects:223+ raise TooManyRedirects()224+225 history.append(r)226 227 url = r.headers['location']228 229+ # 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)233+234 # 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)))238 239 # 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 lines265 version of that.266 267 Otherwise, assumes the data is already encoded appropriately, and268 returns it twice.235-269 """270+271 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 lines279 return data, data280 281 282 def _build_url(self):249- """Build the actual URL to use"""283+ """Build the actual URL to use."""284 251- # 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 ]))292 293 if self._enc_params:294 if urlparse(self.url).query:295 return '%s&%s' % (self.url, self._enc_params)12 unmodified lines308 309 :param anyway: If True, request will be sent, even if it has310 already been sent.311 """312+313 self._checks()314 success = False315 316 # Logging20 unmodified lines337 else:338 req = _Request(url, data=self._enc_data, method=self.method)339 340 if self.headers:303- req.headers.update(self.headers)341+ for k,v in self.headers.iteritems():342+ req.add_header(k, v)343 344 if not self.sent or anyway:345 346 try:347 opener = self._get_opener()309- resp = opener(req)348+ try:349 350+ resp = opener(req, timeout=self.timeout)351+352+ except TypeError, err:353+ # timeout argument is new since Python v2.6354+ if not 'timeout' in str(err):355+ raise356+357+ 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)361+362+ resp = opener(req)363+364+ if settings.timeout_fallback:365+ # restore gobal timeout366+ socket.setdefaulttimeout(old_timeout)367+368 if self.cookiejar is not None:369 self.cookiejar.extract_cookies(resp, req)370 371 except (urllib2.HTTPError, urllib2.URLError), why:2 unmodified lines374 why = Timeout(why)375 376 self._build_response(why, is_error=True)377 321-378 else:379 self._build_response(resp)380 self.response.ok = True381 38 unmodified lines420 421 #: Params handled in _build_url422 return curl_cmd + method_opt + data + header + '"' + self._build_url() + '"'423 368-424 class 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 """430 431 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.432+433 self._content = None434+435 #: Integer Code of responded HTTP Status.436 self.status_code = None437+438 #: 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()442+443+ #: File-like object representation of response (for advanced usage).444+ self.fo = None445+446 #: Final URL location of Response.447 self.url = None448+449 #: True if no :attr:`error` occured.450 self.ok = False451+452 #: Resulting :class:`HTTPError` of request, if one occured.453 self.error = None454+393- #: 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 = []459+397- #: The Request that created the Response.460+ #: The :class:`Request <Request>` that created the Response.461 self.request = None462 463+ #: A dictionary of Cookies the server sent back.464+ self.cookies = None465 466+467 def __repr__(self):468 return '<Response [%s]>' % (self.status_code)469 470 471 def __nonzero__(self):472 """Returns true if :attr:`status_code` is 'OK'."""473+474 return not self.error475 476 410- 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+ """482+483+ if self._content is not None:484 return self._content485 486+ # Read the contents.487+ self._content = self.fo.read()488 489+ # 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+ pass495+496+ # Decode unicode content.497+ if settings.decode_unicode:498+ self._content = get_unicode_from_response(self)499+500+ return self._content501+502+503 def raise_for_status(self):504 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""505 if self.error:506 raise self.error507 508 509+510 class AuthManager(object):511 """Requests Authentication Manager."""512 513 def __new__(cls):65 unmodified lines579 580 581 def reduce_uri(self, uri, default_port=True):582 """Accept authority or URI and extract only the authority and path."""583+584 # note HTTP URLs do not have a userinfo component585 parts = urllib2.urlparse.urlsplit(uri)586+587 if parts[1]:588 # URI589 scheme = parts[0]590 authority = parts[1]2 unmodified lines593 # host or host:port594 scheme = None595 authority = uri596 path = '/'597+598 host, port = urllib2.splitport(authority)599+600 if default_port and port is None and scheme is not None:601 dport = {"http": 80,602 "https": 443,603 }.get(scheme)80 unmodified linesadded:requests/sessions.py+84 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.session5+~~~~~~~~~~~~~~~6+7+This module provides a Session object to manage and persist settings across8+requests (cookies, auth, proxies).9+10+"""11+12+import cookielib13+14+from . import api15+from .utils import add_dict_to_cookiejar16+17+18+19+class Session(object):20+ """A Requests session."""21+22+ __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']23+24+25+ def __init__(self, **kwargs):26+27+ # Set up a CookieJar to be used by default28+ self.cookies = cookielib.FileCookieJar()29+30+ # Map args from kwargs to instance-local variables31+ map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),32+ kwargs.iterkeys(), kwargs.itervalues())33+34+ # Map and wrap requests.api methods35+ self._map_api_methods()36+37+38+ def __repr__(self):39+ return '<requests-client at 0x%x>' % (id(self))40+41+ def __enter__(self):42+ return self43+44+ def __exit__(self, *args):45+ # print args46+ pass47+48+49+ def _map_api_methods(self):50+ """Reads each available method from requests.api and decorates51+ them with a wrapper, which inserts any instance-local attributes52+ (from __attrs__) that have been set, combining them with **kwargs.53+ """54+55+ def pass_args(func):56+ def wrapper_func(*args, **kwargs):57+ inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems()58+ if k in self.__attrs__)59+ # Combine instance-local values with kwargs values, with60+ # priority to values in kwargs61+ kwargs = dict(inst_attrs.items() + kwargs.items())62+63+ # If a session request has a cookie_dict, inject the64+ # values into the existing CookieJar instead.65+ if isinstance(kwargs.get('cookies', None), dict):66+ kwargs['cookies'] = add_dict_to_cookiejar(67+ inst_attrs['cookies'], kwargs['cookies']68+ )69+70+ if kwargs.get('headers', None) and inst_attrs.get('headers', None):71+ kwargs['headers'].update(inst_attrs['headers'])72+73+ return func(*args, **kwargs)74+ return wrapper_func75+76+ # Map and decorate each function available in requests.api77+ map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),78+ api.__all__)79+80+81+def session(**kwargs):82+ """Returns a :class:`Session` for context-managment."""83+84+ return Session(**kwargs)modified:requests/status_codes.py+4 added-4 removed
20 unmodified lines21 208: ('im_used',),22 23 # 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 lines35 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 lines61 450: ('blocked_by_windows_parental_controls', 'parental_controls'),62 499: ('client_closed_request',),63 64 # 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 linesadded:requests/utils.py+165 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.utils5+~~~~~~~~~~~~~~6+7+This module provides utlity functions that are used within Requests8+that are also useful for external consumption.9+10+"""11+12+import cgi13+import cookielib14+import re15+import zlib16+17+18+def dict_from_cookiejar(cj):19+ """Returns a key/value dictionary from a CookieJar.20+21+ :param cj: CookieJar object to extract cookies from.22+ """23+24+ cookie_dict = {}25+26+ 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.value31+32+ return cookie_dict33+34+35+def cookiejar_from_dict(cookie_dict):36+ """Returns a CookieJar from a key/value dictionary.37+38+ :param cookie_dict: Dict of key/values to insert into CookieJar.39+ """40+41+ # return cookiejar if one was passed in42+ if isinstance(cookie_dict, cookielib.CookieJar):43+ return cookie_dict44+45+ # create cookiejar46+ cj = cookielib.CookieJar()47+48+ cj = add_dict_to_cookiejar(cj, cookie_dict)49+50+ return cj51+52+53+def add_dict_to_cookiejar(cj, cookie_dict):54+ """Returns a CookieJar from a key/value dictionary.55+56+ :param cj: CookieJar to insert cookies into.57+ :param cookie_dict: Dict of key/values to insert into CookieJar.58+ """59+60+ for k, v in cookie_dict.items():61+62+ 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+ )81+82+ # add cookie to cookiejar83+ cj.set_cookie(cookie)84+85+ return cj86+87+88+def get_encodings_from_content(content):89+ """Returns encodings from given content string.90+91+ :param content: bytestring to extract encodings from.92+ """93+94+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)95+96+ return charset_re.findall(content)97+98+99+100+def get_encoding_from_headers(headers):101+ """Returns encodings from given HTTP Header Dict.102+103+ :param headers: dictionary to extract encoding from.104+ """105+106+ content_type = headers.get('content-type')107+ content_type, params = cgi.parse_header(content_type)108+109+ if 'charset' in params:110+ return params['charset'].strip("'\"")111+112+113+def get_unicode_from_response(r):114+ """Returns the requested content back in unicode.115+116+ :param r: Reponse object to get unicode content from.117+118+ Tried:119+120+ 1. charset from content-type121+122+ 2. every encodings from ``<meta ... charset=XXX>``123+124+ 3. fall back and replace all unicode characters125+126+ """127+128+ tried_encodings = []129+130+ # Try charset from content-type131+ encoding = get_encoding_from_headers(r.headers)132+133+ if encoding:134+ try:135+ print '!'136+ return unicode(r.content, encoding)137+ except UnicodeError:138+ tried_encodings.append(encoding)139+140+ # Try every encodings from <meta ... charset=XXX>141+ encodings = get_encodings_from_content(r.content)142+143+ for encoding in encodings:144+ if encoding in tried_encodings:145+ continue146+ try:147+148+ return unicode(r.content, encoding)149+ except (UnicodeError, TypeError):150+ tried_encodings.append(encoding)151+152+ # Fall back:153+ try:154+ return unicode(r.content, encoding, errors='replace')155+ except TypeError:156+ return r.content157+158+159+def decode_gzip(content):160+ """Return gzip-decoded string.161+162+ :param content: bytestring to gzip-decode.163+ """164+165+ return zlib.decompress(content, 16+zlib.MAX_WBITS)modified:AUTHORS+10 added-1 removed
29 unmodified lines30 - 潘旭 (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 Makmodified:HISTORY.rst+23 added-3 removed
1 History2 -------3 4-0.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.8+9+10+0.6.1 (2011-08-20)11 ++++++++++++++++++12 7-* 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+* Bugfixes19+20+21+0.6.0 (2011-08-17)22+++++++++++++++++++23+24+* 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 * Bugfixes132 unmodified linesmodified:MANIFEST.in+1 added-1 removed
1-include README.rst LICENSE HISTORY.rst 1+include README.rst LICENSE HISTORY.rst test_requests.pymodified:README.rst+27 added-83 removed
1 Requests: HTTP for Humans2 =========================3 4-Most existing Python modules for dealing HTTP requests are insane. I have to look up *everything* that I want to do. Most of my worst Python experiences are a result of the various built-in HTTP libraries (yes, even worse than Logging).4+Requests is an ISC Licensed HTTP library, written in Python, for human5+beings.6 6-But this one's different. This one's going to be awesome. And simple.7+Most existing Python modules for sending HTTP requests are extremely8+verbose and cumbersome. Python's builtin urllib2 module provides most of9+the HTTP capabilities you should need, but the api is thoroughly broken.10+It requires an enormous amount of work (even method overrides) to11+perform the simplest of tasks.12 8-Really simple.13+Things shouldn't be this way. Not in Python.14 15+::16+17+ >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))18+ >>> r.status_code19+ 20420+ >>> r.headers['content-type']21+ 'application/json'22+ >>> r.content23+ ...24+25+See `the same code, without Requests <https://gist.github.com/973705>`_.26+27+Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,28+**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,29+multipart files, and parameters with simple Python dictionaries, and access the30+response data in the same way. It's powered by urllib2, but it does31+all the hard work and crazy hacks for you.32+33+34 Features35 --------36 37 - Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests40 unmodified lines78 >>> r.content79 '{"authenticated": true, "user": "user"}'80 81 58-59-API60----61-62-**Requests:**63-64-All request functions return a Response object (see below).65-66-If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.67-If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.68-69- HEAD Requests70- >>> requests.head(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})71- <Response [200]>72-73- GET Requests74- >>> requests.get(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})75- <Response [200]>76-77- POST Requests78- >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})79- <Response [200]>80-81- PUT Requests82- >>> requests.put(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})83- <Response [200]>84-85- PATCH Requests86- >>> requests.patch(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})87- <Response [200]>88-89- DELETE Requests90- >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})91- <Response [200]>92-93-94-**Responses:**95-96- Response.status_code97- (Integer) Received HTTP Status Code Response98-99- Response.headers100- ((CaseInsensitive) Dictionary) Received HTTP Response Headers.101-102- Response.content103- (Bytes) Received Content.104-105- Response.history106- (List of Responses) Redirection History.107-108- Response.url109- (String) URL of response. Useful for detecting redirects.110-111- Response.ok112- (Bool) True if no errors occurred during the request, and the status_code is kosher.113-114- Response.cached115- (Bool) True if Response.content is stored within the object.116-117- Response.error118- (HTTPError) If an HTTPError occurred (e.g. status of 404), Otherwise this is None.119-120- Response.raise_for_status()121- Raises HTTPError if a request is not kosher.122-123-124-**HTTP Authentication Registry:**125-126- You can register AuthObjects to automatically enable HTTP Authentication on requests that contain a registered base URL string.127-128- >>> requests.auth_manager.add_auth(url, authobject)129-130-131-82 Installation83 ------------84 85 To install requests, simply: ::13 unmodified lines99 100 If 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_.101 102 153-154-Roadmap155--------156-157-- Sphinx Documentation158-103 .. _`the repository`: http://github.com/kennethreitz/requests104 .. _AUTHORS: http://github.com/kennethreitz/requests/blob/master/AUTHORSmodified:test_requests.py+36 added-20 removed
11 unmodified lines12 import json13 14 import requests15 16+from requests.sessions import Session17 18 19 HTTPBIN_URL = 'http://httpbin.org/'20 HTTPSBIN_URL = 'https://httpbin.ep.io/'110 unmodified lines131 r = requests.patch(httpsbin('patch'))132 self.assertEqual(r.status_code, 200)133 134 134- def test_AUTH_HTTPS_200_OK_GET(self):135+ def test_AUTH_HTTP_200_OK_GET(self):136 137 for service in SERVICES:138 139 auth = ('user', 'pass')140 url = service('basic-auth', 'user', 'pass')140- r = requests.get(url, auth=auth)141 142+ r = requests.get(url, auth=auth)143+ # print r.__dict__144 self.assertEqual(r.status_code, 200)145 146+147 r = requests.get(url)148 self.assertEqual(r.status_code, 200)149 147- # reset auto authentication148- requests.auth_manager.empty()150 150-151 def test_POSTBIN_GET_POST_FILES(self):152 153 for service in SERVICES:154 88 unmodified lines243 r = requests.get(httpbin('gzip'))244 r.content.decode('ascii')245 246 247- def test_autoauth(self):248-249- http_auth = ('user', 'pass')250- requests.auth_manager.add_auth('httpbin.org', http_auth)251-252- r = requests.get(httpbin('basic-auth', 'user', 'pass'))253- self.assertEquals(r.status_code, 200)254-255-256- requests.auth_manager.add_auth('httpbin.ep.io', http_auth)257-258- r = requests.get(httpsbin('basic-auth', 'user', 'pass'))259- self.assertEquals(r.status_code, 200)260-261-247 def test_unicode_get(self):248 249 for service in SERVICES:250 188 unmodified lines439 self.assertEquals(r.status_code, 200)440 self.assertEquals(len(r.history), 3)441 442 443+ def test_session_HTTP_200_OK_GET(self):444+445+ s = Session()446+ r = s.get(httpbin('/'))447+ self.assertEqual(r.status_code, 200)448+449+450+ def test_session_HTTPS_200_OK_GET(self):451+452+ s = Session()453+ r = s.get(httpsbin('/'))454+ self.assertEqual(r.status_code, 200)455+456+457+ def test_session_persistent_headers(self):458+459+ heads = {'User-agent': 'Mozilla/5.0'}460+461+ s = Session()462+ s.headers = heads463+ # Make 2 requests from Session object, should send header both times464+ r1 = s.get(httpbin('user-agent'))465+466+ assert heads['User-agent'] in r1.content467+ r2 = s.get(httpbin('user-agent'))468+469+ assert heads['User-agent'] in r2.content470+ self.assertEqual(r2.status_code, 200)471+472+473+474 if __name__ == '__main__':475 unittest.main()