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
Provenance
- Commit
5b5b3de- Tree
4ec2ba5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
b19d878- Parent 2
1a4dfad
15 files changed+376 added−301 removed
modified:docs/community/out-there.rst+1 added-1 removed
4 unmodified lines5 - `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.10 10-11 Articles & 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 linesmodified:docs/user/advanced.rst+7 added-7 removed
15 unmodified lines16 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:20+ s = requests.session()21 22- 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")24 25- print r.content26- # '{"cookies": {"sessioncookie": "123456789"}}'25+ print r.content26+ # '{"cookies": {"sessioncookie": "123456789"}}'27 28 29 Sessions can also be used to provide default data to the request methods::30 7 unmodified lines38 39 40 .. admonition:: Global Settings41 42- 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).44 45 46 Asynchronous Requests47 ----------------------125 unmodified linesmodified:docs/user/install.rst+1 added-1 removed
16 unmodified lines17 or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::18 19 $ easy_install requests20 21-But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/index.html#pip-compared-to-easy-install>`_.21+But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install>`_.22 23 24 25 Cheeseshop Mirror53 unmodified linesmodified:requests/__init__.py+31 added-2 removed
1 # -*- coding: utf-8 -*-2 3-from core import *4-from core import __version__3+# __4+# /__) _ _ _ _ _/ _5+# / ( (- (/ (/ (- _) / _)6+# /7+8+"""9+requests10+~~~~~~~~11+12+:copyright: (c) 2011 by Kenneth Reitz.13+:license: ISC, see LICENSE for more details.14+15+"""16+17+__title__ = 'requests'18+__version__ = '0.7.0'19+__build__ = 0x00070020+__author__ = 'Kenneth Reitz'21+__license__ = 'ISC'22+__copyright__ = 'Copyright 2011 Kenneth Reitz'23+24+25+from . import utils26+from .models import HTTPError, Request, Response27+from .api import request, get, head, post, patch, put, delete28+from .sessions import session29+from .status_codes import codes30+from .exceptions import (31+ RequestException, AuthenticationError, Timeout, URLRequired,32+ TooManyRedirects33+)modified:requests/api.py+20 added-75 removed
9 unmodified lines10 :license: ISC, see LICENSE for more details.11 12 """13 14-import config15-from .models import Request, Response, AuthObject16-from .status_codes import codes17-from .hooks import dispatch_hook18-from .utils import cookiejar_from_dict, header_expand14+from .sessions import session15 20-16 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')17 18+19 def 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):32 27- """Constructs and sends a :class:`Request <Request>`.28- Returns :class:`Response <Response>` object.29-30- :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- """43-44- method = str(method).upper()45-46- if cookies is None:47- cookies = {}48-49- cookies = cookiejar_from_dict(cookies)50-51- # Expand header values52- if headers:53- for k, v in headers.items() or {}:54- headers[k] = header_expand(v)55-56- 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 )39 71- # Arguments manipulation hook.72- args = dispatch_hook('args', hooks, args)40 74- r = Request(**args)41 76- # Pre-request hook.77- r = dispatch_hook('pre_request', hooks, r)78-79- # Don't send if asked nicely.80- if not return_response:81- return r82-83- # Send the HTTP Request.84- r.send()85-86- # Post-request hook.87- r = dispatch_hook('post_request', hooks, r)88-89- # Response manipulation hook.90- r.response = dispatch_hook('response', hooks, r.response)91-92- return r.response93-94-42 def get(url, **kwargs):96-43 """Sends a GET request. Returns :class:`Response` object.44 45 :param url: URL for the new :class:`Request` object.46 :param **kwargs: Optional arguments that ``request`` takes.47 """48 103-49 kwargs.setdefault('allow_redirects', True)50 return request('GET', url, **kwargs)51 52 37 unmodified lines90 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.91 :param **kwargs: Optional arguments that ``request`` takes.92 """93 149- return request('patch', url, **kwargs)94+ return request('patch', url, data='', **kwargs)95 96 97 def delete(url, **kwargs):98 """Sends a DELETE request. Returns :class:`Response` object.6 unmodified linesdeleted:requests/config.py-68 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.config5-~~~~~~~~~~~~~~~6-7-This module provides the Requests settings feature set.8-9-"""10-11-class Settings(object):12- _singleton = {}13-14- # attributes with defaults15- __attrs__ = []16-17- def __init__(self, **kwargs):18- super(Settings, self).__init__()19-20- self.__dict__ = self._singleton21-22-23- def __call__(self, *args, **kwargs):24- # new instance of class to call25- r = self.__class__()26-27- # cache previous settings for __exit__28- r.__cache = self.__dict__.copy()29- map(self.__cache.setdefault, self.__attrs__)30-31- # set new settings32- self.__dict__.update(*args, **kwargs)33-34- return r35-36-37- def __enter__(self):38- pass39-40-41- def __exit__(self, *args):42-43- # restore cached copy44- self.__dict__.update(self.__cache.copy())45- del self.__cache46-47-48- 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)55-56-57-settings = Settings()58-59-settings.base_headers = {'User-Agent': 'python-requests.org'}60-settings.accept_gzip = True61-settings.proxies = None62-settings.verbose = None63-settings.timeout = None64-settings.max_redirects = 3065-settings.decode_unicode = True66-67-#: Use socket.setdefaulttimeout() as fallback?68-settings.timeout_fallback = Truedeleted:requests/core.py-29 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.core5-~~~~~~~~~~~~~6-7-This module implements the main Requests system.8-9-:copyright: (c) 2011 by Kenneth Reitz.10-:license: ISC, see LICENSE for more details.11-12-"""13-14-__title__ = 'requests'15-__version__ = '0.6.6'16-__build__ = 0x00060617-__author__ = 'Kenneth Reitz'18-__license__ = 'ISC'19-__copyright__ = 'Copyright 2011 Kenneth Reitz'20-21-22-from models import HTTPError, Request, Response23-from api import *24-from exceptions import *25-from sessions import session26-from status_codes import codes27-from config import settings28-29-import utilsadded:requests/defaults.py+38 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.defaults5+~~~~~~~~~~~~~~~~~6+7+This module provides the Requests configuration defaults.8+9+settings parameters:10+11+- :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?18+19+"""20+21+from . import __version__22+23+defaults = dict()24+25+26+defaults['base_headers'] = {27+ 'User-Agent': 'python-requests/%s' % __version__,28+ 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),29+}30+31+defaults['proxies'] = {}32+defaults['verbose'] = None33+defaults['timeout'] = None34+defaults['max_redirects'] = 3035+defaults['decode_unicode'] = True36+defaults['timeout_fallback'] = True37+# defaults['keep_alive'] = True38+# defaults['max_connections'] = 10modified:requests/exceptions.py+4 added-5 removed
1 # -*- coding: utf-8 -*-2 3 """4 requests.exceptions5-~~~~~~~~~~~~~~~5+~~~~~~~~~~~~~~~~~~~6 7+This module contains the set of Requests' exceptions.8+9 """10 11 class RequestException(Exception):12 """There was an ambiguous exception that occurred while handling your13 request."""14 15 class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15- 17+18 class Timeout(RequestException):19 """The request timed out."""20 21 class URLRequired(RequestException):22 """A valid URL is required to make a request."""23 22-class InvalidMethod(RequestException):23- """An inappropriate method was attempted."""24-24 class TooManyRedirects(RequestException):25 """Too many redirects."""modified:requests/models.py+71 added-52 removed
1+2 # -*- coding: utf-8 -*-3 4 """5 requests.models3 unmodified lines9 10 import urllib11 import urllib212 import socket12-import codecs13 import zlib14 15-15 from urllib2 import HTTPError16 from urlparse import urlparse, urlunparse, urljoin17 from datetime import datetime18 20-from .config import settings21-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19 from .structures import CaseInsensitiveDict20 from .packages.poster.encode import multipart_encode21 from .packages.poster.streaminghttp import register_openers, get_handlers25-from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip22+from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)23 from .status_codes import codes27-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects24+from .exceptions import Timeout, URLRequired, TooManyRedirects25+from .monkeys import Request as _Request26+from .monkeys import (27+ HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler,28+ HTTPDigestAuthHandler, HTTPRedirectHandler)29 30 31 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)32 4 unmodified lines37 Requests. Recommended interface is with the Requests functions.38 """39 40 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):55 56 #: Float describes the timeout of the request.57 # (Use socket.setdefaulttimeout() as fallback)58 self.timeout = timeout43 unmodified lines102 #: :class:`AuthObject` to attach to :class:`Request <Request>`.103 self.auth = auth104 105 #: CookieJar to attach to :class:`Request <Request>`.94- self.cookiejar = cookiejar106+ self.cookies = cookies107 108+ #: Dictionary of configurations for this request.109+ self.config = config110+111 #: True if Request has been sent.112 self.sent = False113 114 #: Event-handling hooks.115 self.hooks = hooks116 102- # Header manipulation and defaults.103-104- if settings.accept_gzip:105- settings.base_headers.update({'Accept-Encoding': 'gzip'})106-117 if headers:118 headers = CaseInsensitiveDict(self.headers)119 else:120 headers = CaseInsensitiveDict()121 112- 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] = v125 126 self.headers = headers2 unmodified lines129 def __repr__(self):130 return '<Request [%s]>' % (self.method)131 132 123- def _checks(self):124- """Deterministic checks for consistency."""125-126- if not self.url:127- raise URLRequired128-129-133 def _get_opener(self):134 """Creates appropriate opener object for urllib2."""135 136 _handlers = []137 135- 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))140 141 if self.auth:142 if not isinstance(self.auth.handler,143 (urllib2.AbstractBasicAuthHandler,43 unmodified lines187 188 def build(resp):189 190 response = Response()191+ response.config = self.config192 response.status_code = getattr(resp, 'code', None)193 194 try:195 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))196 response.raw = resp197 194- if self.cookiejar:195- response.cookies = dict_from_cookiejar(self.cookiejar)198+ if self.cookies:199+ response.cookies = dict_from_cookiejar(self.cookies)200 201 202 except AttributeError:203 pass18 unmodified lines222 ):223 224 r.raw.close()225 222- if not len(history) < settings.max_redirects:226+ if not len(history) < self.config.get('max_redirects'):227 raise TooManyRedirects()228 229 history.append(r)230 15 unmodified lines246 else:247 method = self.method248 249 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 lines320 :param anyway: If True, request will be sent, even if it has321 already been sent.322 """323 313- self._checks()324+ # Some people...325+ if not self.url:326+ raise URLRequired327 328 # 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 ))333 321-334+ # Build the URL335 url = self._build_url()323- if self.method in ('GET', 'HEAD', 'DELETE'):324- req = _Request(url, method=self.method)325- else:336 337+ # Attach uploaded files.327- if self.files:328- register_openers()338+ if self.files:339+ register_openers()340 341+ # 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)344 333- datagen, headers = multipart_encode(self.files)334- req = _Request(url, data=datagen, headers=headers, method=self.method)345+ data, headers = multipart_encode(self.files)346 336- else:337- req = _Request(url, data=self._enc_data, method=self.method)347+ else:348+ data = self._enc_data349+ headers = {}350 351+ # Build the Urllib2 Request.352+ req = _Request(url, data=data, headers=headers, method=self.method)353+354+ # 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 lines368 # timeout argument is new since Python v2.6369 if not 'timeout' in str(err):370 raise371 356- 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)376 377 resp = opener(req)378 363- if settings.timeout_fallback:379+ if self.config.get('timeout_fallback'):380 # restore global timeout381 socket.setdefaulttimeout(old_timeout)382 367- 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)385 386 except (urllib2.HTTPError, urllib2.URLError), why:387 if hasattr(why, 'reason'):388 if isinstance(why.reason, socket.timeout):55 unmodified lines444 445 #: A dictionary of Cookies the server sent back.446 self.cookies = None447 448+ #: Dictionary of configurations for this request.449+ self.config = None450 451+452 def __repr__(self):453 return '<Response [%s]>' % (self.status_code)454 455 22 unmodified lines478 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 lines507 except zlib.error:508 pass509 510 # Decode unicode content.492- if settings.decode_unicode:511+ if self.config.get('decode_unicode'):512 self._content = get_unicode_from_response(self)513 514 self._content_consumed = True515 return self._content183 unmodified linesmodified:requests/sessions.py+160 added-42 removed
9 unmodified lines10 """11 12 import cookielib13 14-from . import api15-from .utils import add_dict_to_cookiejar14+from .defaults import defaults15+from .models import Request16+from .hooks import dispatch_hook17+from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18 19 18-20 def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.22 23 If a local key in the dictionary is set to None, it will be removed.1 unmodified line25 26 if default_kwarg is None:27 return local_kwarg28 29+ if isinstance(local_kwarg, basestring):30+ return local_kwarg31+32 if local_kwarg is None:33 return default_kwarg34 35 # Bypass if not a dictionary (e.g. timeout)36 if not hasattr(default_kwarg, 'items'):37 return local_kwarg38 35-36-39 # Update new values.40 kwargs = default_kwarg.copy()41 kwargs.update(local_kwarg)42 7 unmodified lines50 51 class Session(object):52 """A Requests session."""53 52- __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params']54+ __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params', 'config']55 56 57 def __init__(self,58 headers=None,1 unmodified line60 auth=None,61 timeout=None,62 proxies=None,63 hooks=None,62- params=None):64+ params=None,65+ config=None):66 67 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 {}75 76+ for (k, v) in defaults.items():77+ self.config.setdefault(k, v)78+79 # Set up a CookieJar to be used by default80 self.cookies = cookielib.FileCookieJar()81 75- # Map and wrap requests.api methods76- self._map_api_methods()77-78-82 def __repr__(self):83 return '<requests-client at 0x%x>' % (id(self))84 85 def __enter__(self):1 unmodified line87 88 def __exit__(self, *args):89 pass90 88- 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):104+105+ """Constructs and sends a :class:`Request <Request>`.106+ Returns :class:`Response <Response>` object.107+108+ :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 """122 94- def pass_args(func):95- def wrapper_func(*args, **kwargs):123+ method = str(method).upper()124 97- # Argument collector.98- _kwargs = {}125+ if cookies is None:126+ cookies = {}127 100- # 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)130 107- 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)132 112- 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)137 114- # 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+ )153 118- # 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)157 123- return func(*args, **_kwargs)158+ args[attr] = merge_kwargs(local_val, session_val)159 125- return wrapper_func160+ # Arguments manipulation hook.161+ args = dispatch_hook('args', hooks, args)162 127- # 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)164 165+ # Pre-request hook.166+ r = dispatch_hook('pre_request', hooks, r)167 168+ # Don't send if asked nicely.169+ if not return_response:170+ return r171+172+ # Send the HTTP Request.173+ r.send()174+175+ # Post-request hook.176+ r = dispatch_hook('post_request', hooks, r)177+178+ # Response manipulation hook.179+ r.response = dispatch_hook('response', hooks, r.response)180+181+ return r.response182+183+184+ def get(self, url, **kwargs):185+ """Sends a GET request. Returns :class:`Response` object.186+187+ :param url: URL for the new :class:`Request` object.188+ :param **kwargs: Optional arguments that ``request`` takes.189+ """190+191+ kwargs.setdefault('allow_redirects', True)192+ return self.request('GET', url, **kwargs)193+194+195+ def head(self, url, **kwargs):196+ """Sends a HEAD request. Returns :class:`Response` object.197+198+ :param url: URL for the new :class:`Request` object.199+ :param **kwargs: Optional arguments that ``request`` takes.200+ """201+202+ kwargs.setdefault('allow_redirects', True)203+ return self.request('HEAD', url, **kwargs)204+205+206+ def post(self, url, data='', **kwargs):207+ """Sends a POST request. Returns :class:`Response` object.208+209+ :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+ """213+214+ return self.request('post', url, data=data, **kwargs)215+216+217+ def put(self, url, data='', **kwargs):218+ """Sends a PUT request. Returns :class:`Response` object.219+220+ :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+ """224+225+ return self.request('put', url, data=data, **kwargs)226+227+228+ def patch(self, url, data='', **kwargs):229+ """Sends a PATCH request. Returns :class:`Response` object.230+231+ :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+ """235+236+ return self.request('patch', url, data='', **kwargs)237+238+239+ def delete(self, url, **kwargs):240+ """Sends a DELETE request. Returns :class:`Response` object.241+242+ :param url: URL for the new :class:`Request` object.243+ :param **kwargs: Optional arguments that ``request`` takes.244+ """245+246+ return self.request('delete', url, **kwargs)247+248+249+250 def session(**kwargs):251 """Returns a :class:`Session` for context-management."""252 253 return Session(**kwargs)modified:requests/status_codes.py+3 added
54 unmodified lines55 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 linesmodified:HISTORY.rst+14 added-5 removed
1 History2 -------3 4+0.7.0 (2011-10-22)5+++++++++++++++++++6+7+* Sessions are now the primary interface.8+* Deprecated InvalidMethodException.9+* PATCH fix.10+* New config system (no more global settings).11+12+13 0.6.6 (2011-10-19)14 ++++++++++++++++++15 7-* Session parameter bugfix (params merging)16+* Session parameter bugfix (params merging).17 18 19 0.6.5 (2011-10-18)20 ++++++++++++++++++5 unmodified lines26 0.6.4 (2011-10-13)27 ++++++++++++++++++28 29 * 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.34 35 36 0.6.3 (2011-10-13)37 ++++++++++++++++++3 unmodified lines41 42 0.6.2 (2011-10-09)43 ++++++++++++++++++44 36-* GET/HEAD obeys allow_redirects=False45+* GET/HEAD obeys allow_redirects=False.46 47 48 0.6.1 (2011-08-20)49 ++++++++++++++++++156 unmodified linesmodified:Makefile+1 added-1 removed
1 init:2 pip install -r reqs.txt3 4 test:5- nosetests test_requests.py --with-color5+ nosetests test_requests.py6 7 ci: init8 nosetests test_requests.py --with-xunit --xunit-file=junit-report.xml9 7 unmodified linesmodified:test_requests.py+25 added-13 removed
6 unmodified lines7 import cookielib8 import os9 import unittest10 11+import requests12 import envoy13 14 try:15 import omnijson as json16 except ImportError:17 import json18 18-import requests19 20-from requests.sessions import Session20+# TODO: Detect an open port.21+PORT = os.environ.get('HTTPBIN_PORT', '7077')22 22-PORT = os.environ.get('HTTPBIN_PORT', '7045')23-23 HTTPBIN_URL = 'http://0.0.0.0:%s/' % (PORT)24 # HTTPBIN_URL = 'http://127.0.0.1:8000/'25 26 18 unmodified lines45 global _httpbin46 47 if not _httpbin:48 50- 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))50 51+ self.httpbin = c52 _httpbin = True53 time.sleep(1)54 55 1 unmodified line57 def tearDown(self):58 """Teardown."""59 # self.httpbin.kill()60 61+ def test_entry_points(self):62+ import requests63 64+ requests.session65+ requests.session().get66+ requests.session().head67+ requests.get68+ requests.head69+ requests.put70+ requests.patch71+ requests.post72+73+74+75 def test_invalid_url(self):76 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')77 65-78 def test_HTTP_200_OK_GET(self):79 r = requests.get(httpbin('/get'))80 self.assertEqual(r.status_code, 200)81 82 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)85 86 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)89 90 91 def test_HTTP_200_OK_GET_WITH_PARAMS(self):92 heads = {'User-agent': 'Mozilla/5.0'}360 unmodified lines453 454 455 def test_session_HTTP_200_OK_GET(self):456 445- s = Session()457+ s = requests.session()458 r = s.get(httpbin('/get'))459 self.assertEqual(r.status_code, 200)460 461 462 def test_session_persistent_headers(self):463 464 heads = {'User-agent': 'Mozilla/5.0'}465 454- s = Session()466+ s = requests.session()467 s.headers = heads468 469 # Make 2 requests from Session object, should send header both times470 r1 = s.get(httpbin('user-agent'))12 unmodified lines483 def test_session_persistent_params(self):484 485 params = {'a': 'a_test'}486 475- s = Session()487+ s = requests.session()488 s.params = params489 490 # Make 2 requests from Session object, should send header both times491 r1 = s.get(httpbin('get'))21 unmodified lines