Skip to content
Myr

Merge branch 'develop'

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

authored by Kenneth Reitz · committed by Kenneth Reitz · parents b19d878, 1a4dfad · Browse files · 15 files+376 added−301 removed
This commit

State

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

Diff stats

15 files+376 added−301 removed

  • other:+376 added−301 removed

15 files+376 added−301 removed

modified:docs/community/out-there.rst+1 added-1 removed
4 unmodified lines
5- `FacePy <https://github.com/jgorset/facepy>`_, a Python wrapper to the Facebook API.6- `robotframework-requests <https://github.com/bulkan/robotframework-requests>`_, a Robot Framework API wrapper.7- `fullerene <https://github.com/bitprophet/fullerene>`_, a Graphite Dashboard.8- `urbanairship-python <https://github.com/benjaminws/urbanairship-python>`_, a fork of the Urban Airship API wrapper.9- `WhitespaceBot <https://github.com/Gunio/WhitespaceBot/>`_, a project that automatically forks repos, strips trailing whitespace, and sends a pull request.101011Articles & Talks12================13- `Python for the Web <http://gun.io/blog/python-for-the-web/>`_ teaches how to use Python to interact with the web, using Requests.14- `Daniel Greenfield's Review of Requests <http://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_
49 unmodified lines
modified:docs/user/advanced.rst+7 added-7 removed
15 unmodified lines
16A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920 with requests.session() as s:20 s = requests.session()2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")22 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print r.content26 # '{"cookies": {"sessioncookie": "123456789"}}'25 print r.content26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods::30
7 unmodified lines
383940.. admonition:: Global Settings4142 Certain parameters are best set at the ``request.config`` level43 (e.g.. a global proxy, user agent header).42 Certain parameters are best set in the ``config`` dictionary43 (e.g. user agent header).444546Asynchronous Requests47----------------------
125 unmodified lines
modified:docs/user/install.rst+1 added-1 removed
16 unmodified lines
17or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::1819 $ easy_install requests2021But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install>`_.22232425Cheeseshop Mirror
53 unmodified lines
modified:requests/__init__.py+31 added-2 removed
1# -*- coding: utf-8 -*-23from core import *4from core import __version__3# __4# /__) _ _ _ _ _/ _5# / ( (- (/ (/ (- _) / _)6# /78"""9requests10~~~~~~~~1112:copyright: (c) 2011 by Kenneth Reitz.13:license: ISC, see LICENSE for more details.1415"""1617__title__ = 'requests'18__version__ = '0.7.0'19__build__ = 0x00070020__author__ = 'Kenneth Reitz'21__license__ = 'ISC'22__copyright__ = 'Copyright 2011 Kenneth Reitz'232425from . import utils26from .models import HTTPError, Request, Response27from .api import request, get, head, post, patch, put, delete28from .sessions import session29from .status_codes import codes30from .exceptions import (31 RequestException, AuthenticationError, Timeout, URLRequired,32 TooManyRedirects33)
modified:requests/api.py+20 added-75 removed
9 unmodified lines
10:license: ISC, see LICENSE for more details.1112"""1314import config15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict, header_expand14from .sessions import session152016__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')171819def request(method, url,24 params=None, data=None, headers=None, cookies=None, files=None, auth=None,25 timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):20 params=None,21 data=None,22 headers=None,23 cookies=None,24 files=None,25 auth=None,26 timeout=None,27 allow_redirects=False,28 proxies=None,29 hooks=None,30 return_response=True,31 config=None):3227 """Constructs and sends a :class:`Request <Request>`.28 Returns :class:`Response <Response>` object.2930 :param method: method for the new :class:`Request` object.31 :param url: URL for the new :class:`Request` object.32 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.33 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.34 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.35 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.36 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.37 :param auth: (optional) AuthObject to enable Basic HTTP Auth.38 :param timeout: (optional) Float describing the timeout of the request.39 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.40 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.41 :param return_response: (optional) If False, an un-sent Request object will returned.42 """4344 method = str(method).upper()4546 if cookies is None:47 cookies = {}4849 cookies = cookiejar_from_dict(cookies)5051 # Expand header values52 if headers:53 for k, v in headers.items() or {}:54 headers[k] = header_expand(v)5556 args = dict(57 method = method,58 url = url,59 data = data,60 params = params,61 headers = headers,62 cookiejar = cookies,63 files = files,64 auth = auth,65 hooks = hooks,66 timeout = timeout or config.settings.timeout,67 allow_redirects = allow_redirects,68 proxies = proxies or config.settings.proxies,33 s = session()34 return s.request(35 method, url, params, data, headers, cookies, files, auth,36 timeout, allow_redirects, proxies, hooks, return_response,37 config38 )3971 # Arguments manipulation hook.72 args = dispatch_hook('args', hooks, args)4074 r = Request(**args)4176 # Pre-request hook.77 r = dispatch_hook('pre_request', hooks, r)7879 # Don't send if asked nicely.80 if not return_response:81 return r8283 # Send the HTTP Request.84 r.send()8586 # Post-request hook.87 r = dispatch_hook('post_request', hooks, r)8889 # Response manipulation hook.90 r.response = dispatch_hook('response', hooks, r.response)9192 return r.response939442def get(url, **kwargs):9643 """Sends a GET request. Returns :class:`Response` object.4445 :param url: URL for the new :class:`Request` object.46 :param **kwargs: Optional arguments that ``request`` takes.47 """4810349 kwargs.setdefault('allow_redirects', True)50 return request('GET', url, **kwargs)5152
37 unmodified lines
90 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.91 :param **kwargs: Optional arguments that ``request`` takes.92 """93149 return request('patch', url, **kwargs)94 return request('patch', url, data='', **kwargs)959697def delete(url, **kwargs):98 """Sends a DELETE request. Returns :class:`Response` object.
6 unmodified lines
deleted:requests/config.py-68 removed
1# -*- coding: utf-8 -*-23"""4requests.config5~~~~~~~~~~~~~~~67This module provides the Requests settings feature set.89"""1011class Settings(object):12 _singleton = {}1314 # attributes with defaults15 __attrs__ = []1617 def __init__(self, **kwargs):18 super(Settings, self).__init__()1920 self.__dict__ = self._singleton212223 def __call__(self, *args, **kwargs):24 # new instance of class to call25 r = self.__class__()2627 # cache previous settings for __exit__28 r.__cache = self.__dict__.copy()29 map(self.__cache.setdefault, self.__attrs__)3031 # set new settings32 self.__dict__.update(*args, **kwargs)3334 return r353637 def __enter__(self):38 pass394041 def __exit__(self, *args):4243 # restore cached copy44 self.__dict__.update(self.__cache.copy())45 del self.__cache464748 def __getattribute__(self, key):49 if key in object.__getattribute__(self, '__attrs__'):50 try:51 return object.__getattribute__(self, key)52 except AttributeError:53 return None54 return object.__getattribute__(self, key)555657settings = Settings()5859settings.base_headers = {'User-Agent': 'python-requests.org'}60settings.accept_gzip = True61settings.proxies = None62settings.verbose = None63settings.timeout = None64settings.max_redirects = 3065settings.decode_unicode = True6667#: Use socket.setdefaulttimeout() as fallback?68settings.timeout_fallback = True
deleted:requests/core.py-29 removed
1# -*- coding: utf-8 -*-23"""4requests.core5~~~~~~~~~~~~~67This module implements the main Requests system.89:copyright: (c) 2011 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1314__title__ = 'requests'15__version__ = '0.6.6'16__build__ = 0x00060617__author__ = 'Kenneth Reitz'18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'202122from models import HTTPError, Request, Response23from api import *24from exceptions import *25from sessions import session26from status_codes import codes27from config import settings2829import utils
added:requests/defaults.py+38 added
1# -*- coding: utf-8 -*-23"""4requests.defaults5~~~~~~~~~~~~~~~~~67This module provides the Requests configuration defaults.89settings parameters:1011- :base_headers: - Sets default User-Agent to `python-requests.org`12- :accept_gzip: - Whether or not to accept gzip-compressed data13- :proxies: - http proxies?14- :verbose: - display verbose information?15- :timeout: - timeout time until request terminates16- :max_redirects: - maximum number of allowed redirects?17- :decode_unicode: - whether or not to accept unicode?1819"""2021from . import __version__2223defaults = dict()242526defaults['base_headers'] = {27 'User-Agent': 'python-requests/%s' % __version__,28 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),29}3031defaults['proxies'] = {}32defaults['verbose'] = None33defaults['timeout'] = None34defaults['max_redirects'] = 3035defaults['decode_unicode'] = True36defaults['timeout_fallback'] = True37# defaults['keep_alive'] = True38# defaults['max_connections'] = 10
modified:requests/exceptions.py+4 added-5 removed
1# -*- coding: utf-8 -*-23"""4requests.exceptions5~~~~~~~~~~~~~~~5~~~~~~~~~~~~~~~~~~~67This module contains the set of Requests' exceptions.89"""1011class RequestException(Exception):12 """There was an ambiguous exception that occurred while handling your13 request."""1415class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15 1718class Timeout(RequestException):19 """The request timed out."""2021class URLRequired(RequestException):22 """A valid URL is required to make a request."""2322class InvalidMethod(RequestException):23 """An inappropriate method was attempted."""2424class TooManyRedirects(RequestException):25 """Too many redirects."""
modified:requests/models.py+71 added-52 removed
12# -*- coding: utf-8 -*-34"""5requests.models
3 unmodified lines
910import urllib11import urllib212import socket12import codecs13import zlib141515from urllib2 import HTTPError16from urlparse import urlparse, urlunparse, urljoin17from datetime import datetime1820from .config import settings21from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19from .structures import CaseInsensitiveDict20from .packages.poster.encode import multipart_encode21from .packages.poster.streaminghttp import register_openers, get_handlers25from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip22from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)23from .status_codes import codes27from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects24from .exceptions import Timeout, URLRequired, TooManyRedirects25from .monkeys import Request as _Request26from .monkeys import (27 HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler,28 HTTPDigestAuthHandler, HTTPRedirectHandler)293031REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)32
4 unmodified lines
37 Requests. Recommended interface is with the Requests functions.38 """3940 def __init__(self,40 url=None, headers=dict(), files=None, method=None, data=dict(),41 params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,42 allow_redirects=False, proxies=None, hooks=None):41 url=None,42 headers=dict(),43 files=None,44 method=None,45 data=dict(),46 params=dict(),47 auth=None,48 cookies=None,49 timeout=None,50 redirect=False,51 allow_redirects=False,52 proxies=None,53 hooks=None,54 config=None):5556 #: Float describes the timeout of the request.57 # (Use socket.setdefaulttimeout() as fallback)58 self.timeout = timeout
43 unmodified lines
102 #: :class:`AuthObject` to attach to :class:`Request <Request>`.103 self.auth = auth104105 #: CookieJar to attach to :class:`Request <Request>`.94 self.cookiejar = cookiejar106 self.cookies = cookies107108 #: Dictionary of configurations for this request.109 self.config = config110111 #: True if Request has been sent.112 self.sent = False113114 #: Event-handling hooks.115 self.hooks = hooks116102 # Header manipulation and defaults.103104 if settings.accept_gzip:105 settings.base_headers.update({'Accept-Encoding': 'gzip'})106117 if headers:118 headers = CaseInsensitiveDict(self.headers)119 else:120 headers = CaseInsensitiveDict()121112 for (k, v) in settings.base_headers.items():122 for (k, v) in self.config.get('base_headers', {}).items():123 if k not in headers:124 headers[k] = v125126 self.headers = headers
2 unmodified lines
129 def __repr__(self):130 return '<Request [%s]>' % (self.method)131132123 def _checks(self):124 """Deterministic checks for consistency."""125126 if not self.url:127 raise URLRequired128129133 def _get_opener(self):134 """Creates appropriate opener object for urllib2."""135136 _handlers = []137135 if self.cookiejar is not None:136 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))138 if self.cookies is not None:139 _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))140141 if self.auth:142 if not isinstance(self.auth.handler,143 (urllib2.AbstractBasicAuthHandler,
43 unmodified lines
187188 def build(resp):189190 response = Response()191 response.config = self.config192 response.status_code = getattr(resp, 'code', None)193194 try:195 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))196 response.raw = resp197194 if self.cookiejar:195 response.cookies = dict_from_cookiejar(self.cookiejar)198 if self.cookies:199 response.cookies = dict_from_cookiejar(self.cookies)200201202 except AttributeError:203 pass
18 unmodified lines
222 ):223224 r.raw.close()225222 if not len(history) < settings.max_redirects:226 if not len(history) < self.config.get('max_redirects'):227 raise TooManyRedirects()228229 history.append(r)230
15 unmodified lines
246 else:247 method = self.method248249 request = Request(246 url, self.headers, self.files, method,247 self.data, self.params, self.auth, self.cookiejar,248 redirect=True250 url=url,251 headers=self.headers,252 files=self.files,253 method=method,254 # data=self.data,255 # params=self.params,256 auth=self.auth,257 cookies=self.cookies,258 redirect=True,259 config=self.config260 )261 request.send()262 r = request.response263
56 unmodified lines
320 :param anyway: If True, request will be sent, even if it has321 already been sent.322 """323313 self._checks()324 # Some people...325 if not self.url:326 raise URLRequired327328 # Logging316 if settings.verbose:317 settings.verbose.write('%s %s %s\n' % (329 if self.config.get('verbose'):330 self.config.get('verbose').write('%s %s %s\n' % (331 datetime.now().isoformat(), self.method, self.url332 ))333321334 # Build the URL335 url = self._build_url()323 if self.method in ('GET', 'HEAD', 'DELETE'):324 req = _Request(url, method=self.method)325 else:336337 # Attach uploaded files.327 if self.files:328 register_openers()338 if self.files:339 register_openers()340341 # Add form-data to the multipart.330 if self.data:331 self.files.update(self.data)342 if self.data:343 self.files.update(self.data)344333 datagen, headers = multipart_encode(self.files)334 req = _Request(url, data=datagen, headers=headers, method=self.method)345 data, headers = multipart_encode(self.files)346336 else:337 req = _Request(url, data=self._enc_data, method=self.method)347 else:348 data = self._enc_data349 headers = {}350351 # Build the Urllib2 Request.352 req = _Request(url, data=data, headers=headers, method=self.method)353354 # Add the headers to the request.355 if self.headers:356 for k,v in self.headers.iteritems():357 req.add_header(k, v)358
9 unmodified lines
368 # timeout argument is new since Python v2.6369 if not 'timeout' in str(err):370 raise371356 if settings.timeout_fallback:372 if self.config.get('timeout_fallback'):373 # fall-back and use global socket timeout (This is not thread-safe!)374 old_timeout = socket.getdefaulttimeout()375 socket.setdefaulttimeout(self.timeout)376377 resp = opener(req)378363 if settings.timeout_fallback:379 if self.config.get('timeout_fallback'):380 # restore global timeout381 socket.setdefaulttimeout(old_timeout)382367 if self.cookiejar is not None:368 self.cookiejar.extract_cookies(resp, req)383 if self.cookies is not None:384 self.cookies.extract_cookies(resp, req)385386 except (urllib2.HTTPError, urllib2.URLError), why:387 if hasattr(why, 'reason'):388 if isinstance(why.reason, socket.timeout):
55 unmodified lines
444445 #: A dictionary of Cookies the server sent back.446 self.cookies = None447448 #: Dictionary of configurations for this request.449 self.config = None450451452 def __repr__(self):453 return '<Response [%s]>' % (self.status_code)454455
22 unmodified lines
478 gen = generate()479 if 'gzip' in self.headers.get('content-encoding', ''):480 gen = stream_decode_gzip(gen)481 if decode_unicode is None:463 decode_unicode = settings.decode_unicode482 decode_unicode = self.config.get('decode_unicode')483 if decode_unicode:484 gen = stream_decode_response_unicode(gen, self)485 return gen486
20 unmodified lines
507 except zlib.error:508 pass509510 # Decode unicode content.492 if settings.decode_unicode:511 if self.config.get('decode_unicode'):512 self._content = get_unicode_from_response(self)513514 self._content_consumed = True515 return self._content
183 unmodified lines
modified:requests/sessions.py+160 added-42 removed
9 unmodified lines
10"""1112import cookielib1314from . import api15from .utils import add_dict_to_cookiejar14from .defaults import defaults15from .models import Request16from .hooks import dispatch_hook17from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18191820def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.2223 If a local key in the dictionary is set to None, it will be removed.
1 unmodified line
2526 if default_kwarg is None:27 return local_kwarg2829 if isinstance(local_kwarg, basestring):30 return local_kwarg3132 if local_kwarg is None:33 return default_kwarg3435 # Bypass if not a dictionary (e.g. timeout)36 if not hasattr(default_kwarg, 'items'):37 return local_kwarg38353639 # Update new values.40 kwargs = default_kwarg.copy()41 kwargs.update(local_kwarg)42
7 unmodified lines
5051class Session(object):52 """A Requests session."""5352 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params']54 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params', 'config']555657 def __init__(self,58 headers=None,
1 unmodified line
60 auth=None,61 timeout=None,62 proxies=None,63 hooks=None,62 params=None):64 params=None,65 config=None):6667 self.headers = headers or {}68 self.cookies = cookies or {}69 self.auth = auth70 self.timeout = timeout71 self.proxies = proxies or {}72 self.hooks = hooks or {}73 self.params = params or {}74 self.config = config or {}7576 for (k, v) in defaults.items():77 self.config.setdefault(k, v)7879 # Set up a CookieJar to be used by default80 self.cookies = cookielib.FileCookieJar()8175 # Map and wrap requests.api methods76 self._map_api_methods()777882 def __repr__(self):83 return '<requests-client at 0x%x>' % (id(self))8485 def __enter__(self):
1 unmodified line
8788 def __exit__(self, *args):89 pass9088 def _map_api_methods(self):89 """Reads each available method from requests.api and decorates90 them with a wrapper, which inserts any instance-local attributes91 (from __attrs__) that have been set, combining them with **kwargs.91 def request(self, method, url,92 params=None,93 data=None,94 headers=None,95 cookies=None,96 files=None,97 auth=None,98 timeout=None,99 allow_redirects=False,100 proxies=None,101 hooks=None,102 return_response=True,103 config=None):104105 """Constructs and sends a :class:`Request <Request>`.106 Returns :class:`Response <Response>` object.107108 :param method: method for the new :class:`Request` object.109 :param url: URL for the new :class:`Request` object.110 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.111 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.112 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.113 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.114 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.115 :param auth: (optional) AuthObject to enable Basic HTTP Auth.116 :param timeout: (optional) Float describing the timeout of the request.117 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.118 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.119 :param return_response: (optional) If False, an un-sent Request object will returned.120 :param config: (optional) A configuration dictionary.121 """12294 def pass_args(func):95 def wrapper_func(*args, **kwargs):123 method = str(method).upper()12497 # Argument collector.98 _kwargs = {}125 if cookies is None:126 cookies = {}127100 # If a session request has a cookie_dict, inject the101 # values into the existing CookieJar instead.102 if isinstance(kwargs.get('cookies', None), dict):103 kwargs['cookies'] = add_dict_to_cookiejar(104 self.cookies, kwargs['cookies']105 )128 if isinstance(cookies, dict):129 cookies = add_dict_to_cookiejar(self.cookies, cookies)130107 for attr in self.__attrs__:108 # for attr in ['headers',]:109 s_val = self.__dict__.get(attr)110 r_val = kwargs.get(attr)131 cookies = cookiejar_from_dict(cookies)132112 new_attr = merge_kwargs(r_val, s_val)133 # Expand header values134 if headers:135 for k, v in headers.items() or {}:136 headers[k] = header_expand(v)137114 # Skip attributes that were set to None.115 if new_attr is not None:116 _kwargs[attr] = new_attr138 args = dict(139 method=method,140 url=url,141 data=data,142 params=params,143 headers=headers,144 cookies=cookies,145 files=files,146 auth=auth,147 hooks=hooks,148 timeout=timeout,149 allow_redirects=allow_redirects,150 proxies=proxies,151 config=config152 )153118 # Make sure we didn't miss anything.119 for (k, v) in kwargs.items():120 if k not in _kwargs:121 _kwargs[k] = v154 for attr in self.__attrs__:155 session_val = getattr(self, attr, None)156 local_val = args.get(attr)157123 return func(*args, **_kwargs)158 args[attr] = merge_kwargs(local_val, session_val)159125 return wrapper_func160 # Arguments manipulation hook.161 args = dispatch_hook('args', hooks, args)162127 # Map and decorate each function available in requests.api128 map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),129 api.__all__)163 r = Request(**args)164165 # Pre-request hook.166 r = dispatch_hook('pre_request', hooks, r)167168 # Don't send if asked nicely.169 if not return_response:170 return r171172 # Send the HTTP Request.173 r.send()174175 # Post-request hook.176 r = dispatch_hook('post_request', hooks, r)177178 # Response manipulation hook.179 r.response = dispatch_hook('response', hooks, r.response)180181 return r.response182183184 def get(self, url, **kwargs):185 """Sends a GET request. Returns :class:`Response` object.186187 :param url: URL for the new :class:`Request` object.188 :param **kwargs: Optional arguments that ``request`` takes.189 """190191 kwargs.setdefault('allow_redirects', True)192 return self.request('GET', url, **kwargs)193194195 def head(self, url, **kwargs):196 """Sends a HEAD request. Returns :class:`Response` object.197198 :param url: URL for the new :class:`Request` object.199 :param **kwargs: Optional arguments that ``request`` takes.200 """201202 kwargs.setdefault('allow_redirects', True)203 return self.request('HEAD', url, **kwargs)204205206 def post(self, url, data='', **kwargs):207 """Sends a POST request. Returns :class:`Response` object.208209 :param url: URL for the new :class:`Request` object.210 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.211 :param **kwargs: Optional arguments that ``request`` takes.212 """213214 return self.request('post', url, data=data, **kwargs)215216217 def put(self, url, data='', **kwargs):218 """Sends a PUT request. Returns :class:`Response` object.219220 :param url: URL for the new :class:`Request` object.221 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.222 :param **kwargs: Optional arguments that ``request`` takes.223 """224225 return self.request('put', url, data=data, **kwargs)226227228 def patch(self, url, data='', **kwargs):229 """Sends a PATCH request. Returns :class:`Response` object.230231 :param url: URL for the new :class:`Request` object.232 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.233 :param **kwargs: Optional arguments that ``request`` takes.234 """235236 return self.request('patch', url, data='', **kwargs)237238239 def delete(self, url, **kwargs):240 """Sends a DELETE request. Returns :class:`Response` object.241242 :param url: URL for the new :class:`Request` object.243 :param **kwargs: Optional arguments that ``request`` takes.244 """245246 return self.request('delete', url, **kwargs)247248249250def session(**kwargs):251 """Returns a :class:`Session` for context-management."""252253 return Session(**kwargs)
modified:requests/status_codes.py+3 added
54 unmodified lines
55 423: ('locked',),56 424: ('failed_dependency', 'dependency'),57 425: ('unordered_collection', 'unordered'),58 426: ('upgrade_required', 'upgrade'),59 428: ('precondition_required', 'precondition'),60 429: ('too_many_requests', 'too_many'),61 431: ('header_fields_too_large', 'fields_too_large'),62 444: ('no_response', 'none'),63 449: ('retry_with', 'retry'),64 450: ('blocked_by_windows_parental_controls', 'parental_controls'),65 499: ('client_closed_request',),
21 unmodified lines
modified:HISTORY.rst+14 added-5 removed
1History2-------340.7.0 (2011-10-22)5++++++++++++++++++67* Sessions are now the primary interface.8* Deprecated InvalidMethodException.9* PATCH fix.10* New config system (no more global settings).1112130.6.6 (2011-10-19)14++++++++++++++++++157* Session parameter bugfix (params merging)16* Session parameter bugfix (params merging).1718190.6.5 (2011-10-18)20++++++++++++++++++
5 unmodified lines
260.6.4 (2011-10-13)27++++++++++++++++++2829* Automatic decoding of unicode, based on HTTP Headers.21* New ``decode_unicode`` setting22* Removal of ``r.read/close`` methods30* New ``decode_unicode`` setting.31* Removal of ``r.read/close`` methods.32* New ``r.faw`` interface for advanced response usage.*24* Automatic expansion of parameterized headers33* Automatic expansion of parameterized headers.3435360.6.3 (2011-10-13)37++++++++++++++++++
3 unmodified lines
41420.6.2 (2011-10-09)43++++++++++++++++++4436* GET/HEAD obeys allow_redirects=False45* GET/HEAD obeys allow_redirects=False.4647480.6.1 (2011-08-20)49++++++++++++++++++
156 unmodified lines
modified:Makefile+1 added-1 removed
1init:2 pip install -r reqs.txt34test:5 nosetests test_requests.py --with-color5 nosetests test_requests.py67ci: init8 nosetests test_requests.py --with-xunit --xunit-file=junit-report.xml9
7 unmodified lines
modified:test_requests.py+25 added-13 removed
6 unmodified lines
7import cookielib8import os9import unittest1011import requests12import envoy1314try:15 import omnijson as json16except ImportError:17 import json1818import requests1920from requests.sessions import Session20# TODO: Detect an open port.21PORT = os.environ.get('HTTPBIN_PORT', '7077')2222PORT = os.environ.get('HTTPBIN_PORT', '7045')2323HTTPBIN_URL = 'http://0.0.0.0:%s/' % (PORT)24# HTTPBIN_URL = 'http://127.0.0.1:8000/'2526
18 unmodified lines
45 global _httpbin4647 if not _httpbin:4850 self.httpbin = envoy.connect('gunicorn httpbin:app --bind=0.0.0.0:%s' % (PORT))49 c = envoy.connect('gunicorn httpbin:app --bind=0.0.0.0:%s' % (PORT))5051 self.httpbin = c52 _httpbin = True53 time.sleep(1)5455
1 unmodified line
57 def tearDown(self):58 """Teardown."""59 # self.httpbin.kill()6061 def test_entry_points(self):62 import requests6364 requests.session65 requests.session().get66 requests.session().head67 requests.get68 requests.head69 requests.put70 requests.patch71 requests.post72737475 def test_invalid_url(self):76 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')776578 def test_HTTP_200_OK_GET(self):79 r = requests.get(httpbin('/get'))80 self.assertEqual(r.status_code, 200)8182 def test_HTTP_302_ALLOW_REDIRECT_GET(self):71 r = requests.get(httpbin('redirect', '1'))72 self.assertEqual(r.status_code, 200)83 r = requests.get(httpbin('redirect', '1'))84 self.assertEqual(r.status_code, 200)8586 def test_HTTP_302_GET(self):75 r = requests.get(httpbin('redirect', '1'), allow_redirects=False)76 self.assertEqual(r.status_code, 302)87 r = requests.get(httpbin('redirect', '1'), allow_redirects=False)88 self.assertEqual(r.status_code, 302)899091 def test_HTTP_200_OK_GET_WITH_PARAMS(self):92 heads = {'User-agent': 'Mozilla/5.0'}
360 unmodified lines
453454455 def test_session_HTTP_200_OK_GET(self):456445 s = Session()457 s = requests.session()458 r = s.get(httpbin('/get'))459 self.assertEqual(r.status_code, 200)460461462 def test_session_persistent_headers(self):463464 heads = {'User-agent': 'Mozilla/5.0'}465454 s = Session()466 s = requests.session()467 s.headers = heads468469 # Make 2 requests from Session object, should send header both times470 r1 = s.get(httpbin('user-agent'))
12 unmodified lines
483 def test_session_persistent_params(self):484485 params = {'a': 'a_test'}486475 s = Session()487 s = requests.session()488 s.params = params489490 # Make 2 requests from Session object, should send header both times491 r1 = s.get(httpbin('get'))
21 unmodified lines