Skip to content
Myr

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

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

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

22 files+1048 added−242 removed

added:docs/community/faq.rst+43 added
1.. _faq:23Frequently Asked Questions4==========================56This part of the documentation covers common questions about Requests.78Why not Httplib2?9-----------------1011Chris Adams gave an excellent summary on12`Hacker News <http://news.ycombinator.com/item?id=2884406>`_:1314 httplib2 is part of why you should use requests: it's far more respectable15 as a client but not as well documented and it still takes way too much code16 for basic operations. I appreciate what httplib2 is trying to do, that17 there's a ton of hard low-level annoyances in building a modern HTTP18 client, but really, just use requests instead. Kenneth Reitz is very19 motivated and he gets the degree to which simple things should be simple20 whereas httplib2 feels more like an academic exercise than something21 people should use to build production systems[1].2223 Disclosure: I'm listed in the requests AUTHORS file but can claim credit24 for, oh, about 0.0001% of the awesomeness.2526 1. http://code.google.com/p/httplib2/issues/detail?id=96 is a good example:27 an annoying bug which affect many people, there was a fix available for28 months, which worked great when I applied it in a fork and pounded a couple29 TB of data through it, but it took over a year to make it into trunk and30 even longer to make it onto PyPI where any other project which required "31 httplib2" would get the working version.323334Python 3 Support?35-----------------3637It's on the way.383940Keep-alive Support?41-------------------4243It's on the way.
added:docs/community/support.rst+37 added
1.. _support:23Support4=======56If you have a questions or issues about Requests, there are serveral options:78Send a Tweet9------------1011If your question is less than 140 characters, feel free to send a tweet to12`@kennethreitz <http://twitter.com/kennethreitz>`_.131415File an Issue16-------------1718If you notice some unexpected behavior in Requests, or want to see support19for a new feature,20`file an issue on GitHub <https://github.com/kennethreitz/requests/issues>`_.212223E-mail24------2526I'm more than happy to answer any personal or in-depth questions about27Requests. Feel free to email28`requests@kennethreitz.com <mailto:requests@kennethreitz.com>`_.293031IRC32---3334The official Freenode channel for Requests is35`#python-requests <irc://irc.freenode.net/python-requests>`_3637I'm also available as **kennethreitz** on Freenode.
added:docs/community/updates.rst+31 added
1.. _updates:23Updates4=======56If you'd like to stay up to date on the community and development of Requests,7there are serveral options:89GitHub10------1112The best way to track the development of Requests is through13`the GitHub repo <https://github.com/kennethreitz/requests>`_.1415Twitter16-------1718I often tweet about new features and releases of Requests.1920Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.21222324Mailing List25------------2627There's a low-volume mailing list for Requests. To subscribe to the28mailing list, send an email to29`requests@librelist.org <mailto:requests@librelist.org>`_.3031
added:docs/dev/authors.rst+5 added
1Authors2=======345.. include:: ../../AUTHORS
modified:docs/user/advanced.rst+136 added
1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.789Session Objects10---------------1112The Session object allows you to persist certain parameters across13requests. It also establishes a CookieJar and passes it along14to any requests made from the Session instance.1516A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920 with requests.session() as s:2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print r.content262728Sessions can also be used to provide default data to the request methods::2930 headers = {'x-test': 'true'}31 auth = ('user', 'pass')3233 with requests.session(auth=auth, headers=headers) as c:3435 # both 'x-test' and 'x-test2' are sent36 c.get('http://httpbin.org/headers', header={'x-test2', 'true'})373839.. admonition:: Global Settings4041 Certain parameters are best set at the ``request.config`` level42 (e.g.. a global proxy, user agent header).434445Event Hooks46-----------4748Requests has a hook system that you can use to manipulate portions of49the request process, or signal event handling.5051Available hooks:5253``args``:54 A dictionary of the arguments being sent to Request().5556``pre_request``:57 The Request object, directly before being sent.5859``post_request``:60 The Request object, directly after being sent.6162``response``:63 The response generated from a Request.646566You can assign a hook function on a per-request basis by passing a67``{hook_name: callback_function}`` dictionary to the ``hooks`` request68paramaeter::6970 hooks=dict(args=print_url)7172That ``callback_function`` will receive a chunk of data as its first73argument.7475::7677 def print_url(args):78 print args['url']7980If an error occurs while executing your callback, a warning is given.8182If the callback function returns a value, it is assumed that it is to83replace the data that was passed in. If the function doesn't return84anything, nothing else is effected.8586Let's print some request method arguments at runtime::8788 >>> requests.get('http://httpbin', hooks=dict(args=print_url))89 http://httpbin90 <Response [200]>9192Let's hijack some arguments this time with a new callback::9394 def hack_headers(args):95 if not args[headers]:96 args['headers'] = dict()9798 args['headers'].update({'X-Testing': 'True'})99100 return args101102 hooks = dict(args=hack_headers)103 headers = dict(yo=dawg)104105And give it a try::106107 >>> 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 }122123124125Verbose Logging126---------------127128If you want to get a good look at what HTTP requests are being sent129by your application, you can turn on verbose logging.130131To do so, just configure Requests with a stream to write to::132133 >>> 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 lines
14 $ pip install requests1516or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::1718 $ easy_install install requests18 $ easy_install requests1920But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21222324Cheeseshop Mirror25-----------------2627If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <pip.kreitz.co/>`_::27If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::2829 $ pip install -i http://pip.kreitz.co/simple requests303132Get the Code33------------3435Requsts is actively developed on GitHub, where the code is35Requests is actively developed on GitHub, where the code is36`always available <https://github.com/kennethreitz/requests>`_.3738You can either clone the public repository::39
14 unmodified lines
modified:docs/user/quickstart.rst+98 added-48 removed
1Feature Overview2================1.. _quickstart:24Requests is designed to solve a 90% use case — making simple requests. While most5HTTP libraries are extremely extensible, they often attempt to support the entire HTTP Spec.6This often leads to extremely messy and cumbersome APIs, as is the case with urllib2. Requests abandons support for edge-cases, and focuses on the essentials.3Quickstart4==========56.. module:: requests.models79.. _features:8Eager to get started? This page gives a good introduction in how to get started with Requests. This assumes you already have Requests installed. If you do not, head over to the :ref:`Installation <install>` section.911Requests Can:12-------------10First, make sure that:1114- Make **GET**, **POST**, **PUT**, **DELETE**, and **HEAD** requests.15- Handle HTTP and HTTPS Requests16- Add Request headers (with a simple dictionary)17- URLEncode your Form Data (with a simple dictionary)18- Add Multi-part File Uploads (with a simple dictionary)19- Handle CookieJars (with a single parameter)20- Add HTTP Authentication (with a single parameter)21- Handle redirects (with history)22- Automatically decompress GZip'd responses23- Support Unicode URLs24- Gracefully timeout25- Interface with Eventlet & Gevent12* Requests is :ref:`installed <install>`13* Requests is :ref:`up-to-date <updates>`141528Requests Can't:29---------------16Lets gets started with some simple use cases and examples.1731- Handle Caching32- Handle Keep-Alives1819Make a GET Request20------------------2135Quickstart36==========22Making a standard request with Requests is very simple.2324Let's get GitHub's public timeline ::2539GET Request40-----------26 r = requests.get('https://github.com/timeline.json')2728Now, we have a :class:`Response` object called ``r``. We can get all the information we need from this.2943Adding Parameters44-----------------3031Response Content32----------------3334We can read the content of the server's response::3548Adding Headers49--------------36 >>> r.content37 '[{"repository":{"open_issues":0,"url":"https://github.com/...383940Response Status Codes41---------------------4253HTTP Basic Auth54---------------43We can check the response status code::4445 >>> r.status_code46 2004757Tracking Redirects58------------------48Requests also comes with a built-in status code lookup object for easy49reference::5051 >>> r.status_code == requests.codes.ok52 True5354If we made a bad request, we can raise it with55:class:`Response.raise_for_status()`::5657 >>> _r = requests.get('http://httpbin.org/status/404')58 >>> _r.status_code59 4046063HTTP POST (Form Data)64---------------------61 >>> _r.raise_for_status()62 Traceback (most recent call last):63 File "requests/models.py", line 394, in raise_for_status64 raise self.error65 urllib2.HTTPError: HTTP Error 404: NOT FOUND6667But, sice our ``status_code`` was ``200``, when we call it::6867HTTP POST (Binary Data)68-----------------------69 >>> r.raise_for_status()70 None7172All is well.7371HTTP POST (Multipart Files)72---------------------------7475Response Headers76----------------7775HTTP PUT76--------78We can view the server's response headers with a simple Python dictionary79interface::8081 >>> r.headers82 {83 'status': '200 OK',84 'content-encoding': 'gzip',85 'transfer-encoding': 'chunked',86 'connection': 'close',87 'server': 'nginx/1.0.4',88 'x-runtime': '148ms',89 'etag': '"e1ca502697e5c9317743dc078f67693f"',90 'content-type': 'application/json; charset=utf-8'91 }9279HTTP DELETE80-----------93The dictionary is special, though: it's made just for HTTP headers. According to `RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP94Headers are case-insensitive.9596So, we can access the headers using any capitalization we want::9783HTTP HEAD84---------98 >>> r.headers['Content-Type']99 'application/json; charset=utf-8'100101 >>> r.headers.get('content-type')102 'application/json; charset=utf-8'103104If a header doesn't exist in the Response, its value defaults to ``None``::105106 >>> r.headers['X-Random']107 None108109110Cookies111-------112113If a response contains some Cookies, you can get quick access to them::114115 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'116 >>> r = requests.get(url)117118 >>> print r.cookies119 {'requests-is': 'awesome'}120121The underlying CookieJar is also available for more advanced handing::122123 >>> r.request.cookiejar124 <cookielib.CookieJar>125126To send your own cookies to the server, you can use the ``cookies``127parameter::128129 >>> url = 'http://httpbin.org/cookies'130 >>> cookies = dict(cookies_are='working')131132 >>> r = requests.get(url, cookies=cookies)133 >>> r.content134 '{"cookies": {"cookies_are": "working"}}'
modified:docs/conf.py+1 added-1 removed
153 unmodified lines
154# If true, the index is split into individual pages for each letter.155#html_split_index = False156157# If true, links to the reST sources are added to the pages.158html_show_sourcelink = True158html_show_sourcelink = False159160# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.161html_show_sphinx = False162
82 unmodified lines
modified:docs/index.rst+29 added-7 removed
11 unmodified lines
1213Most existing Python modules for sending HTTP requests are extremely verbose14and cumbersome. Python's builtin **urllib2** module provides most of15the HTTP capabilities you should need, but the api is thoroughly **broken**.16It requires an *enormous* amount of work (even method overrides) to perform the simplest of tasks.16It requires an *enormous* amount of work (even method overrides) to perform17the simplest of tasks.1819Things shouldn’t be this way. Not in Python.2021::2223 >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))24 >>> r.status_code24 20025 20426 >>> r.headers['content-type']27 'application/json'28 >>> r.content29 ...3031See `the same code, without Requests <https://gist.github.com/973705>`_.3233Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,
7 unmodified lines
4142`Twitter, Inc <http://twitter.com>`_ uses Requests internally.4344**Daniel Greenfeld**42 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to @kennethreitz's request library. Today has been AWESOME.45 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to46 @kennethreitz's request library. Today has been AWESOME.4748**Kenny Meyers**45 Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful, simple, Pythonic.49 Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,50 simple, Pythonic.5152**Rich Leland**53 Requests is awesome. That is all.5455**Steve Pike**51 I can never remember how to do it the regular way. ``import requests; requests.get()`` is just so easy!56 I can never remember how to do it the regular way.57 ``import requests; requests.get()`` is just so easy!585960User Guide61----------6257This part of the documentation, which is mostly prose, begins with some background information about Requests, then focuses on step-by-step instructions for getting the most out of Requests.63This part of the documentation, which is mostly prose, begins with some64background information about Requests, then focuses on step-by-step65instructions for getting the most out of Requests.6667.. toctree::68 :maxdepth: 26970 user/intro71 user/install64.. user/quickstart72 user/quickstart73 user/advanced747576Community Guide77-----------------7879This part of the documentation, which is mostly prose, details the80Requests ecosystem and community.8182.. toctree::83 :maxdepth: 28485 community/faq86 community/support87 community/updates8889API Documentation90-----------------9192If you are looking for information on a specific function, class or method,
15 unmodified lines
108 :maxdepth: 2109110 dev/internals111 dev/todo112 dev/authors
modified:requests/api.py+43 added-43 removed
10 unmodified lines
1112"""1314import config15from .models import Request, Response, AuthManager, AuthObject, auth_manager15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict1920from urlparse import urlparse2122__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')2324def request(method, url,25 params=None, data=None, headers=None, cookies=None, files=None, auth=None,22 timeout=None, allow_redirects=False, proxies=None):26 timeout=None, allow_redirects=False, proxies=None, hooks=None):2724 """Constructs and sends a :class:`Request <models.Request>`. Returns :class:`Response <models.Response>` object.28 """Constructs and sends a :class:`Request <models.Request>`.29 Returns :class:`Response <models.Response>` object.3031 :param method: method for the new :class:`Request` object.32 :param url: URL for the new :class:`Request` object.33 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
6 unmodified lines
40 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.41 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.42 """4339 r = Request(44 if cookies is None:45 cookies = {}4647 cookies = cookiejar_from_dict(cookies)4849 args = dict(50 method = method,51 url = url,52 data = data,53 params = params,54 headers = headers,55 cookiejar = cookies,56 files = files,47 auth = auth or auth_manager.get_auth(url),57 auth = auth,58 timeout = timeout or config.settings.timeout,59 allow_redirects = allow_redirects,50 proxies = proxies or config.settings.proxies60 proxies = proxies or config.settings.proxies,61 )6263 # Arguments manipulation hook.64 args = dispatch_hook('args', hooks, args)6566 r = Request(hooks=hooks, **args)6768 # Pre-request hook.69 r = dispatch_hook('pre_request', hooks, r)7071 # Send the HTTP Request.72 r.send()7374 # Post-request hook.75 r = dispatch_hook('post_request', hooks, r)7677 # Response manipulation hook.78 r.response = dispatch_hook('response', hooks, r.response)7980 return r.response818258def get(url,59 params=None, headers=None, cookies=None, auth=None, timeout=None,60 proxies=None):83def get(url, **kwargs):8485 """Sends a GET request. Returns :class:`Response` object.8687 :param url: URL for the new :class:`Request` object.
4 unmodified lines
92 :param timeout: (optional) Float describing the timeout of the request.93 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.94 """9573 return request('GET', url,74 params=params, headers=headers, cookies=cookies, auth=auth,75 timeout=timeout, proxies=proxies)96 return request('GET', url, **kwargs)979878def head(url,79 params=None, headers=None, cookies=None, auth=None, timeout=None,80 proxies=None):99def head(url, **kwargs):100101 """Sends a HEAD request. Returns :class:`Response` object.102103 :param url: URL for the new :class:`Request` object.
4 unmodified lines
108 :param timeout: (optional) Float describing the timeout of the request.109 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.110 """11193 return request('HEAD', url,94 params=params, headers=headers, cookies=cookies, auth=auth,95 timeout=timeout, proxies=proxies)112 return request('HEAD', url, **kwargs)11311498def post(url,99 data='', headers=None, files=None, cookies=None, auth=None, timeout=None,100 allow_redirects=False, params=None, proxies=None):115def post(url, data='', **kwargs):116117 """Sends a POST request. Returns :class:`Response` object.118119 :param url: URL for the new :class:`Request` object.
7 unmodified lines
127 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.128 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.129 """130116 return request('POST', url,117 params=params, data=data, headers=headers, files=files,118 cookies=cookies, auth=auth, timeout=timeout,119 allow_redirects=allow_redirects, proxies=proxies)131 return request('POST', url, data=data, **kwargs)132133122def put(url, data='', headers=None, files=None, cookies=None, auth=None,123 timeout=None, allow_redirects=False, params=None, proxies=None):134def put(url, data='', **kwargs):135 """Sends a PUT request. Returns :class:`Response` object.136137 :param url: URL for the new :class:`Request` object.138 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
6 unmodified lines
145 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.146 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.147 """148138 return request('PUT', url,139 params=params, data=data, headers=headers, files=files,140 cookies=cookies, auth=auth, timeout=timeout,141 allow_redirects=allow_redirects, proxies=proxies)149 return request('PUT', url, data=data, **kwargs)150151144def patch(url, data='', headers=None, files=None, cookies=None, auth=None,145 timeout=None, allow_redirects=False, params=None, proxies=None):152def patch(url, data='', **kwargs):153 """Sends a PATCH request. Returns :class:`Response` object.154155 :param url: URL for the new :class:`Request` object.156 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
6 unmodified lines
163 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.164 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.165 """166160 return request('PATCH', url,161 params=params, data=data, headers=headers, files=files,162 cookies=cookies, auth=auth, timeout=timeout,163 allow_redirects=allow_redirects, proxies=proxies)167 return request('PATCH', url, **kwargs)168169166def delete(url,167 params=None, headers=None, cookies=None, auth=None, timeout=None,168 allow_redirects=False, proxies=None):170def delete(url, **kwargs):171172 """Sends a DELETE request. Returns :class:`Response` object.173174 :param url: URL for the new :class:`Request` object.
5 unmodified lines
180 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.181 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.182 """183182 return request('DELETE', url,183 params=params, headers=headers, cookies=cookies, auth=auth,184 timeout=timeout, allow_redirects=allow_redirects, proxies=proxies)184 return request('DELETE', url, **kwargs)
modified:requests/config.py+8 added-1 removed
10 unmodified lines
11class Settings(object):12 _singleton = {}1314 # attributes with defaults15 __attrs__ = ('timeout', 'verbose')15 __attrs__ = []1617 def __init__(self, **kwargs):18 super(Settings, self).__init__()19
32 unmodified lines
52 except AttributeError:53 return None54 return object.__getattribute__(self, key)555657settings = Settings()5859settings.base_headers = {'User-Agent': 'python-requests.org'}60settings.accept_gzip = True61settings.proxies = None62settings.verbose = None63settings.timeout = None6465#: Use socket.setdefaulttimeout() as fallback?66settings.timeout_fallback = True
modified:requests/core.py+5 added-3 removed
10 unmodified lines
1112"""1314__title__ = 'requests'15__version__ = '0.5.1'16__build__ = 0x00050115__version__ = '0.6.0'16__build__ = 0x00060017__author__ = 'Kenneth Reitz'18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'202122from models import HTTPError, auth_manager22from models import HTTPError23from api import *24from exceptions import *25from sessions import session26from status_codes import codes27from config import settings
added:requests/hooks.py+40 added
1# -*- coding: utf-8 -*-23"""4requests.hooks5~~~~~~~~~~~~~~67This module provides the capabilities for the Requests hooks system.89Available hooks:1011``args``:12 A dictionary of the arguments being sent to Request().1314``pre_request``:15 The Request object, directly before being sent.1617``post_request``:18 The Request object, directly after being sent.1920``response``:21 The response generated from a Request.2223"""2425import warnings262728def dispatch_hook(key, hooks, hook_data):29 """Dipatches a hook dictionary on a given peice of data."""3031 hooks = hooks or dict()3233 if key in hooks:34 try:35 return hooks.get(key).__call__(hook_data) or hook_data3637 except Exception, why:38 warnings.warn(str(why))3940 return hook_data
modified:requests/models.py+64 added-17 removed
18 unmodified lines
19from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers23from .utils import dict_from_cookiejar24from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects252627REDIRECT_STATI = (301, 302, 303, 307)
8 unmodified lines
3637 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):4141 socket.setdefaulttimeout(timeout)42 #: Float describ the timeout of the request.43 # (Use socket.setdefaulttimeout() as fallback)44 self.timeout = timeout4546 #: Request URL.47 self.url = url4849 #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.50 self.headers = headers5152 #: Dictionary of files to multipart upload (``{filename: content}``).53 self.files = files5455 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.56 self.method = method5758 #: Dictionary or byte of request body data to attach to the59 #: :class:`Request <models.Request>`.60 self.data = None6162 #: Dictionary or byte of querystring data to attach to the63 #: :class:`Request <models.Request>`.64 self.params = None6566 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history67 #: and HTTPError storage).68 self.redirect = redirect6970 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)71 self.allow_redirects = allow_redirects7273 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})74 self.proxies = proxies7576 self.data, self._enc_data = self._encode_params(data)
6 unmodified lines
83 if isinstance(auth, (list, tuple)):84 auth = AuthObject(*auth)85 if not auth:86 auth = auth_manager.get_auth(self.url)8788 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.89 self.auth = auth9091 #: CookieJar to attach to :class:`Request <models.Request>`.92 self.cookiejar = cookiejar9394 #: True if Request has been sent.95 self.sent = False9697 #: Dictionary of event hook callbacks.98 self.hooks = hooks99100101 # Header manipulation and defaults.102103 if settings.accept_gzip:104 settings.base_headers.update({'Accept-Encoding': 'gzip'})
38 unmodified lines
143 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))144145 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 lines
175176 return opener.open177178161 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."""181182 def build(resp):183
4 unmodified lines
188 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))189 response.read = resp.read190 response._resp = resp191 response._close = resp.close192193 if self.cookiejar:194195 response.cookies = dict_from_cookiejar(self.cookiejar)196197198 except AttributeError:199 pass200201 if is_error:202 response.error = resp203204 response.url = getattr(resp, 'url', None)205206 return response207
21 unmodified lines
229 url = r.headers['location']230231 # 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)))234235 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4236 if r.status_code is 303:237 method = 'GET'
10 unmodified lines
248249 r.history = history250251 self.response = r252 self.response.request = self253254255 @staticmethod256 def _encode_params(data):
18 unmodified lines
275 return data, data276277278 def _build_url(self):252 """Build the actual URL to use"""279 """Build the actual URL to use."""280281 # Support for unicode domain names and paths.282 scheme, netloc, path, params, query, fragment = urlparse(self.url)283 netloc = netloc.encode('idna')
20 unmodified lines
304305 :param anyway: If True, request will be sent, even if it has306 already been sent.307 """308309 self._checks()310 success = False311312 # Logging
20 unmodified lines
333 else:334 req = _Request(url, data=self._enc_data, method=self.method)335336 if self.headers:309 req.headers.update(self.headers)337 for k,v in self.headers.iteritems():338 req.add_header(k, v)339340 if not self.sent or anyway:341342 try:343 opener = self._get_opener()315 resp = opener(req)344 try:345346 resp = opener(req, timeout=self.timeout)347348 except TypeError, err:349 # timeout argument is new since Python v2.6350 if not 'timeout' in str(err):351 raise352353 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)357358 resp = opener(req)359360 if settings.timeout_fallback:361 # restore gobal timeout362 socket.setdefaulttimeout(old_timeout)363364 if self.cookiejar is not None:365 self.cookiejar.extract_cookies(resp, req)366367 except (urllib2.HTTPError, urllib2.URLError), why:368 if hasattr(why, 'reason'):369 if isinstance(why.reason, socket.timeout):370 why = Timeout(why)371325 self._build_response(why)326 if not self.redirect:327 self.response.error = why372 self._build_response(why, is_error=True)373374375 else:376 self._build_response(resp)377 self.response.ok = True378333 self.response.cached = False334 else:335 self.response.cached = True379380 self.sent = self.response.ok381339382 return self.sent383384385
20 unmodified lines
406 #: 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 = None417418419 def __repr__(self):420 return '<Response [%s]>' % (self.status_code)
101 unmodified lines
522523524 def reduce_uri(self, uri, default_port=True):525 """Accept authority or URI and extract only the authority and path."""526527 # note HTTP URLs do not have a userinfo component528 parts = urllib2.urlparse.urlsplit(uri)529530 if parts[1]:531 # URI532 scheme = parts[0]533 authority = parts[1]
2 unmodified lines
536 # host or host:port537 scheme = None538 authority = uri539 path = '/'540541 host, port = urllib2.splitport(authority)542543 if default_port and port is None and scheme is not None:544 dport = {"http": 80,545 "https": 443,546 }.get(scheme)
80 unmodified lines
added:requests/sessions.py+84 added
1# -*- coding: utf-8 -*-23"""4requests.session5~~~~~~~~~~~~~~~67This module provides a Session object to manage and persist settings across8requests (cookies, auth, proxies).910"""1112import cookielib1314from . import api15from .utils import add_dict_to_cookiejar16171819class Session(object):20 """A Requests session."""2122 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']232425 def __init__(self, **kwargs):2627 # Set up a CookieJar to be used by default28 self.cookies = cookielib.FileCookieJar()2930 # Map args from kwargs to instance-local variables31 map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),32 kwargs.iterkeys(), kwargs.itervalues())3334 # Map and wrap requests.api methods35 self._map_api_methods()363738 def __repr__(self):39 return '<requests-client at 0x%x>' % (id(self))4041 def __enter__(self):42 return self4344 def __exit__(self, *args):45 # print args46 pass474849 def _map_api_methods(self):50 """Reads each available method from requests.api and decorates51 them with a wrapper, which inserts any instance-local attributes52 (from __attrs__) that have been set, combining them with **kwargs.53 """5455 def pass_args(func):56 def wrapper_func(*args, **kwargs):57 inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems()58 if k in self.__attrs__)59 # Combine instance-local values with kwargs values, with60 # priority to values in kwargs61 kwargs = dict(inst_attrs.items() + kwargs.items())6263 # If a session request has a cookie_dict, inject the64 # values into the existing CookieJar instead.65 if isinstance(kwargs.get('cookies', None), dict):66 kwargs['cookies'] = add_dict_to_cookiejar(67 inst_attrs['cookies'], kwargs['cookies']68 )6970 if kwargs.get('headers', None) and inst_attrs.get('headers', None):71 kwargs['headers'].update(inst_attrs['headers'])7273 return func(*args, **kwargs)74 return wrapper_func7576 # Map and decorate each function available in requests.api77 map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),78 api.__all__)798081def session(**kwargs):82 """Returns a :class:`Session` for context-managment."""8384 return Session(**kwargs)
added:requests/status_codes.py+83 added
1# -*- coding: utf-8 -*-23from .structures import LookupDict45_codes = {67 # Informational.8 100: ('continue',),9 101: ('switching_protocols',),10 102: ('processing',),11 103: ('checkpoint',),12 122: ('uri_too_long', 'request_uri_too_long'),13 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/'),14 201: ('created',),15 202: ('accepted',),16 203: ('non_authoritative_info', 'non_authoritative_information'),17 204: ('no_content',),18 205: ('reset_content', 'reset'),19 206: ('partial_content', 'partial'),20 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),21 208: ('im_used',),2223 # Redirection.24 300: ('multiple_choices',),25 301: ('moved_permanently', 'moved'),26 302: ('found',),27 302: ('see_other', 'other'),28 304: ('not_modified',),29 305: ('use_proxy',),30 306: ('switch_proxy',),31 307: ('temporary_redirect', 'temporary_moved', 'temporary'),32 308: ('resume_incomplete', 'resume'),3334 # Client Error.35 400: ('bad_request', 'bad'),36 401: ('unauthorized',),37 402: ('payment_required', 'payment'),38 403: ('forbidden',),39 404: ('not_found',),40 405: ('method_not_allowed', 'not_allowed'),41 406: ('not_acceptable',),42 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),43 408: ('request_timeout', 'timeout'),44 409: ('conflict',),45 410: ('gone',),46 411: ('length_required',),47 412: ('precondition_failed', 'precondition'),48 413: ('request_entity_too_large',),49 414: ('request_uri_too_large',),50 415: ('unspported_media_type', 'unspported_media', 'media_type'),51 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),52 417: ('expectation_failed',),53 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),54 422: ('unprocessable_entity', 'unprocessable'),55 423: ('locked',),56 424: ('failed_depdendency', 'depdendency'),57 425: ('unordered_collection', 'unordered'),58 426: ('upgrade_required', 'upgrade'),59 444: ('no_response', 'none'),60 449: ('retry_with', 'retry'),61 450: ('blocked_by_windows_parental_controls', 'parental_controls'),62 499: ('client_closed_request',),6364 # Server Error.65 500: ('internal_server_error', 'server_error'),66 501: ('not_implemented',),67 502: ('bad_gateway',),68 503: ('service_unavailable', 'unavailable'),69 504: ('gateway_timeout',),70 505: ('http_version_not_supported', 'http_version'),71 506: ('variant_also_negotiates',),72 507: ('insufficient_storage',),73 509: ('bandwidth_limit_exceeded', 'bandwidth'),74 510: ('not_extended',),75}7677codes = LookupDict(name='status_codes')7879for (code, titles) in _codes.items():80 for title in titles:81 setattr(codes, title, code)82 if not title.startswith('\\'):83 setattr(codes, title.upper(), code)
modified:requests/structures.py+18 added
43 unmodified lines
44 if key in self:45 return self[key]46 else:47 return default4849class LookupDict(dict):50 """Dictionary lookup object."""5152 def __init__(self, name=None):53 self.name = name54 super(LookupDict, self).__init__()5556 def __repr__(self):57 return '<lookup \'%s\'>' % (self.name)5859 def __getitem__(self, key):60 # We allow fall-through here, so values default to None6162 return self.__dict__.get(key, None)6364 def get(self, key, default=None):65 return self.__dict__.get(key, default)
added:requests/utils.py+72 added
1# -*- coding: utf-8 -*-23"""4requests.utils5~~~~~~~~~~~~~~67This module provides utlity functions that are used within Requests8that are also useful for external consumption.910"""1112import cookielib131415def dict_from_cookiejar(cookiejar):16 """Returns a key/value dictionary from a CookieJar."""1718 cookie_dict = {}1920 for _, cookies in cookiejar._cookies.items():21 for _, cookies in cookies.items():22 for cookie in cookies.values():23 # print cookie24 cookie_dict[cookie.name] = cookie.value2526 return cookie_dict272829def cookiejar_from_dict(cookie_dict):30 """Returns a CookieJar from a key/value dictionary."""3132 # return cookiejar if one was passed in33 if isinstance(cookie_dict, cookielib.CookieJar):34 return cookie_dict3536 # create cookiejar37 cj = cookielib.CookieJar()3839 cj = add_dict_to_cookiejar(cj, cookie_dict)4041 return cj424344def add_dict_to_cookiejar(cj, cookie_dict):45 """Returns a CookieJar from a key/value dictionary."""4647 for k, v in cookie_dict.items():4849 cookie = cookielib.Cookie(50 version=0,51 name=k,52 value=v,53 port=None,54 port_specified=False,55 domain='',56 domain_specified=False,57 domain_initial_dot=False,58 path='/',59 path_specified=True,60 secure=False,61 expires=None,62 discard=True,63 comment=None,64 comment_url=None,65 rest={'HttpOnly': None},66 rfc2109=False67 )6869 # add cookie to cookiejar70 cj.set_cookie(cookie)7172 return cj
modified:AUTHORS+5 added-1 removed
28 unmodified lines
29- 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
1History2-------3450.6.0 (2011-09-??)6++++++++++++++++++78* New callback hook system9* New persistient sessions object and context manager10* Transparent Dict-cookie handling11* status code reference object12* Removed Response.cached13* Added Response.request14* all args are kwargs15* Relative redirect support16* HTTPError handling improvements17* Improved https testing18* Bugfixes19200.5.1 (2011-07-23)21++++++++++++++++++2223* International Domain Name Support!
127 unmodified lines
modified:README.rst+1 added-1 removed
81 unmodified lines
82 >>> requests.put(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})83 <Response [200]>8485 PATCH Requests86 >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})86 >>> requests.patch(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})87 <Response [200]>8889 DELETE Requests90 >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})
70 unmodified lines
modified:test_requests.py+226 added-117 removed
11 unmodified lines
12 import json1314import requests1516from requests.sessions import Session171819HTTPBIN_URL = 'http://httpbin.org/'20HTTPSBIN_URL = 'https://httpbin.ep.io/'
13 unmodified lines
3435 return HTTPSBIN_URL + '/'.join(suffix)363738SERVICES = (httpbin, httpsbin)39404142class RequestsTestSuite(unittest.TestCase):43 """Requests test cases."""4445
85 unmodified lines
131 r = requests.patch(httpsbin('patch'))132 self.assertEqual(r.status_code, 200)133134131 def test_AUTH_HTTPS_200_OK_GET(self):132 auth = ('user', 'pass')133 url = httpsbin('basic-auth', 'user', 'pass')134 r = requests.get(url, auth=auth)135 def test_AUTH_HTTP_200_OK_GET(self):136136 self.assertEqual(r.status_code, 200)137 for service in SERVICES:138138 r = requests.get(url)139 self.assertEqual(r.status_code, 200)139 auth = ('user', 'pass')140 url = service('basic-auth', 'user', 'pass')141141 # reset auto authentication142 requests.auth_manager.empty()142 r = requests.get(url, auth=auth)143 # print r.__dict__144 self.assertEqual(r.status_code, 200)145146147 r = requests.get(url)148 self.assertEqual(r.status_code, 200)149150151 def test_POSTBIN_GET_POST_FILES(self):146 url = httpbin('post')147 post = requests.post(url).raise_for_status()152149 post = requests.post(url, data={'some': 'data'})150 self.assertEqual(post.status_code, 200)153 for service in SERVICES:154152 post2 = requests.post(url, files={'some': open('test_requests.py')})153 self.assertEqual(post2.status_code, 200)155 url = service('post')156 post = requests.post(url).raise_for_status()157155 post3 = requests.post(url, data='[{"some": "json"}]')156 self.assertEqual(post3.status_code, 200)158 post = requests.post(url, data={'some': 'data'})159 self.assertEqual(post.status_code, 200)160161 post2 = requests.post(url, files={'some': open('test_requests.py')})162 self.assertEqual(post2.status_code, 200)163164 post3 = requests.post(url, data='[{"some": "json"}]')165 self.assertEqual(post3.status_code, 200)166167168 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):169161 url = httpbin('post')162 post = requests.post(url, files={'some': open('test_requests.py')}, data={'some': 'data'})163 self.assertEqual(post.status_code, 200)170 for service in SERVICES:171172 url = service('post')173 post = requests.post(url,174 files={'some': open('test_requests.py')},175 data={'some': 'data'})176177 self.assertEqual(post.status_code, 200)178179180 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):181168 url = httpbin('post')182 for service in SERVICES:183170 post2 = requests.post(url, files={'some': open('test_requests.py')},171 headers = {'User-Agent': 'requests-tests'})184 url = service('post')185173 self.assertEqual(post2.status_code, 200)186 post2 = requests.post(url,187 files={'some': open('test_requests.py')},188 headers = {'User-Agent': 'requests-tests'})189190 self.assertEqual(post2.status_code, 200)191192193 def test_nonzero_evaluation(self):177 r = requests.get(httpbin('status', '500'))178 self.assertEqual(bool(r), False)194180 r = requests.get(httpbin('/'))181 self.assertEqual(bool(r), True)195 for service in SERVICES:196197 r = requests.get(service('status', '500'))198 self.assertEqual(bool(r), False)199200 r = requests.get(service('/'))201 self.assertEqual(bool(r), True)202203204 def test_request_ok_set(self):185 r = requests.get(httpbin('status', '404'))186 self.assertEqual(r.ok, False)205206 for service in SERVICES:207208 r = requests.get(service('status', '404'))209 self.assertEqual(r.ok, False)210211212 def test_status_raising(self):213 r = requests.get(httpbin('status', '404'))214 self.assertRaises(requests.HTTPError, r.raise_for_status)215
27 unmodified lines
243 r = requests.get(httpbin('gzip'))244 r.content.decode('ascii')245246224 def test_autoauth(self):225226 http_auth = ('user', 'pass')227 requests.auth_manager.add_auth('httpbin.org', http_auth)228229 r = requests.get(httpbin('basic-auth', 'user', 'pass'))230 self.assertEquals(r.status_code, 200)231232247 def test_unicode_get(self):248235 url = httpbin('/')249 for service in SERVICES:250237 requests.get(url, params={'foo': u'føø'})238 requests.get(url, params={u'føø': u'føø'})239 requests.get(url, params={'føø': 'føø'})240 requests.get(url, params={'foo': u'foo'})241 requests.get(httpbin('ø'), params={'foo': u'foo'})251 url = service('/')252253 requests.get(url, params={'foo': u'føø'})254 requests.get(url, params={u'føø': u'føø'})255 requests.get(url, params={'føø': 'føø'})256 requests.get(url, params={'foo': u'foo'})257 requests.get(service('ø'), params={'foo': u'foo'})258259260 def test_httpauth_recursion(self):261262 http_auth = ('user', 'BADpass')263264 for service in SERVICES:247 r = requests.get(httpbin('basic-auth', 'user', 'pass'), auth=http_auth)248 self.assertEquals(r.status_code, 401)265 r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)266 self.assertEquals(r.status_code, 401)267268269 def test_settings(self):270
8 unmodified lines
279 requests.get(httpbin(''))280281282 def test_urlencoded_post_data(self):265 r = requests.post(httpbin('post'), data=dict(test='fooaowpeuf'))266 self.assertEquals(r.status_code, 200)267 self.assertEquals(r.headers['content-type'], 'application/json')268 self.assertEquals(r.url, httpbin('post'))269 rbody = json.loads(r.content)270 self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))271 self.assertEquals(rbody.get('data'), '')283284 for service in SERVICES:285286 r = requests.post(service('post'), data=dict(test='fooaowpeuf'))287288 self.assertEquals(r.status_code, 200)289 self.assertEquals(r.headers['content-type'], 'application/json')290 self.assertEquals(r.url, service('post'))291292 rbody = json.loads(r.content)293294 self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))295 self.assertEquals(rbody.get('data'), '')296297298 def test_nonurlencoded_post_data(self):275 r = requests.post(httpbin('post'), data='fooaowpeuf')276 self.assertEquals(r.status_code, 200)277 self.assertEquals(r.headers['content-type'], 'application/json')278 self.assertEquals(r.url, httpbin('post'))279 rbody = json.loads(r.content)280 # Body wasn't valid url encoded data, so the server returns None as281 # "form" and the raw body as "data".282 self.assertEquals(rbody.get('form'), None)283 self.assertEquals(rbody.get('data'), 'fooaowpeuf')299300 for service in SERVICES:301302 r = requests.post(service('post'), data='fooaowpeuf')303304 self.assertEquals(r.status_code, 200)305 self.assertEquals(r.headers['content-type'], 'application/json')306 self.assertEquals(r.url, service('post'))307308 rbody = json.loads(r.content)309 # Body wasn't valid url encoded data, so the server returns None as310 # "form" and the raw body as "data".311 self.assertEquals(rbody.get('form'), None)312 self.assertEquals(rbody.get('data'), 'fooaowpeuf')313314315 def test_urlencoded_post_querystring(self):287 r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'))288 self.assertEquals(r.status_code, 200)289 self.assertEquals(r.headers['content-type'], 'application/json')290 self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))291 rbody = json.loads(r.content)292 self.assertEquals(rbody.get('form'), {}) # No form supplied293 self.assertEquals(rbody.get('data'), '')316317 for service in SERVICES:318319 r = requests.post(service('post'), params=dict(test='fooaowpeuf'))320321 self.assertEquals(r.status_code, 200)322 self.assertEquals(r.headers['content-type'], 'application/json')323 self.assertEquals(r.url, service('post?test=fooaowpeuf'))324325 rbody = json.loads(r.content)326 self.assertEquals(rbody.get('form'), {}) # No form supplied327 self.assertEquals(rbody.get('data'), '')328329330 def test_nonurlencoded_post_querystring(self):297 r = requests.post(httpbin('post'), params='fooaowpeuf')298 self.assertEquals(r.status_code, 200)299 self.assertEquals(r.headers['content-type'], 'application/json')300 self.assertEquals(r.url, httpbin('post?fooaowpeuf'))301 rbody = json.loads(r.content)302 self.assertEquals(rbody.get('form'), {}) # No form supplied303 self.assertEquals(rbody.get('data'), '')331332 for service in SERVICES:333334 r = requests.post(service('post'), params='fooaowpeuf')335336 self.assertEquals(r.status_code, 200)337 self.assertEquals(r.headers['content-type'], 'application/json')338 self.assertEquals(r.url, service('post?fooaowpeuf'))339340 rbody = json.loads(r.content)341 self.assertEquals(rbody.get('form'), {}) # No form supplied342 self.assertEquals(rbody.get('data'), '')343344345 def test_urlencoded_post_query_and_data(self):307 r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'),308 data=dict(test2="foobar"))309 self.assertEquals(r.status_code, 200)310 self.assertEquals(r.headers['content-type'], 'application/json')311 self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))312 rbody = json.loads(r.content)313 self.assertEquals(rbody.get('form'), dict(test2='foobar'))314 self.assertEquals(rbody.get('data'), '')346347 for service in SERVICES:348349 r = requests.post(350 service('post'),351 params=dict(test='fooaowpeuf'),352 data=dict(test2="foobar"))353354 self.assertEquals(r.status_code, 200)355 self.assertEquals(r.headers['content-type'], 'application/json')356 self.assertEquals(r.url, service('post?test=fooaowpeuf'))357358 rbody = json.loads(r.content)359 self.assertEquals(rbody.get('form'), dict(test2='foobar'))360 self.assertEquals(rbody.get('data'), '')361362363 def test_nonurlencoded_post_query_and_data(self):318 r = requests.post(httpbin('post'), params='fooaowpeuf',319 data="foobar")320 self.assertEquals(r.status_code, 200)321 self.assertEquals(r.headers['content-type'], 'application/json')322 self.assertEquals(r.url, httpbin('post?fooaowpeuf'))323 rbody = json.loads(r.content)324 self.assertEquals(rbody.get('form'), None)325 self.assertEquals(rbody.get('data'), 'foobar')364365 for service in SERVICES:366367 r = requests.post(service('post'),368 params='fooaowpeuf', data="foobar")369370 self.assertEquals(r.status_code, 200)371 self.assertEquals(r.headers['content-type'], 'application/json')372 self.assertEquals(r.url, service('post?fooaowpeuf'))373374 rbody = json.loads(r.content)375376 self.assertEquals(rbody.get('form'), None)377 self.assertEquals(rbody.get('data'), 'foobar')378379380 def test_idna(self):381 r = requests.get(u'http://➡.ws/httpbin')382 assert 'httpbin' in r.url383384385 def test_urlencoded_get_query_multivalued_param(self):332 r = requests.get(httpbin('get'), params=dict(test=['foo','baz']))333 self.assertEquals(r.status_code, 200)334 self.assertEquals(r.url, httpbin('get?test=foo&test=baz'))386387 for service in SERVICES:388389 r = requests.get(service('get'), params=dict(test=['foo','baz']))390 self.assertEquals(r.status_code, 200)391 self.assertEquals(r.url, service('get?test=foo&test=baz'))392393394 def test_urlencoded_post_querystring_multivalued(self):337 r = requests.post(httpbin('post'), params=dict(test=['foo','baz']))338 self.assertEquals(r.status_code, 200)339 self.assertEquals(r.headers['content-type'], 'application/json')340 self.assertEquals(r.url, httpbin('post?test=foo&test=baz'))341 rbody = json.loads(r.content)342 self.assertEquals(rbody.get('form'), {}) # No form supplied343 self.assertEquals(rbody.get('data'), '')395396 for service in SERVICES:397398 r = requests.post(service('post'), params=dict(test=['foo','baz']))399 self.assertEquals(r.status_code, 200)400 self.assertEquals(r.headers['content-type'], 'application/json')401 self.assertEquals(r.url, service('post?test=foo&test=baz'))402403 rbody = json.loads(r.content)404 self.assertEquals(rbody.get('form'), {}) # No form supplied405 self.assertEquals(rbody.get('data'), '')406407408 def test_urlencoded_post_query_multivalued_and_data(self):346 r = requests.post(httpbin('post'), params=dict(test=['foo','baz']),347 data=dict(test2="foobar",test3=['foo','baz']))348 self.assertEquals(r.status_code, 200)349 self.assertEquals(r.headers['content-type'], 'application/json')350 self.assertEquals(r.url, httpbin('post?test=foo&test=baz'))351 rbody = json.loads(r.content)352 self.assertEquals(rbody.get('form'), dict(test2='foobar',test3='foo'))353 self.assertEquals(rbody.get('data'), '')409410 for service in SERVICES:411412 r = requests.post(413 service('post'),414 params=dict(test=['foo','baz']),415 data=dict(test2="foobar",test3=['foo','baz']))416417 self.assertEquals(r.status_code, 200)418 self.assertEquals(r.headers['content-type'], 'application/json')419 self.assertEquals(r.url, service('post?test=foo&test=baz'))420 rbody = json.loads(r.content)421 self.assertEquals(rbody.get('form'), dict(test2='foobar',test3='foo'))422 self.assertEquals(rbody.get('data'), '')423424425 def test_redirect_history(self):357 r = requests.get(httpbin('redirect', '3'))358 self.assertEquals(r.status_code, 200)359 self.assertEquals(len(r.history), 3)426361 r = requests.get(httpsbin('redirect', '3'))362 self.assertEquals(r.status_code, 200)363 self.assertEquals(len(r.history), 3)427 for service in SERVICES:428429 r = requests.get(service('redirect', '3'))430 self.assertEquals(r.status_code, 200)431 self.assertEquals(len(r.history), 3)432433434 def test_relative_redirect_history(self):435436 for service in SERVICES:437438 r = requests.get(service('relative-redirect', '3'))439 self.assertEquals(r.status_code, 200)440 self.assertEquals(len(r.history), 3)441442443 def test_session_HTTP_200_OK_GET(self):444445 s = Session()446 r = s.get(httpbin('/'))447 self.assertEqual(r.status_code, 200)448449450 def test_session_HTTPS_200_OK_GET(self):451452 s = Session()453 r = s.get(httpsbin('/'))454 self.assertEqual(r.status_code, 200)455456457 def test_session_persistent_headers(self):458459 heads = {'User-agent': 'Mozilla/5.0'}460461 s = Session()462 s.headers = heads463 # Make 2 requests from Session object, should send header both times464 r1 = s.get(httpbin('user-agent'))465466 assert heads['User-agent'] in r1.content467 r2 = s.get(httpbin('user-agent'))468469 assert heads['User-agent'] in r2.content470 self.assertEqual(r2.status_code, 200)471472473474if __name__ == '__main__':475 unittest.main()