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