Merge branch 'release/0.3.3'
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 fec0d1a, 01b22a7 · Browse files · 8 files·+452 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+452 added−31 removed
- other:+452 added−31 removed
Provenance
- Commit
7215452- Tree
4b4d1b5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
fec0d1a- Parent 2
01b22a7
8 files changed+452 added−31 removed
modified:docs/conf.py+2 added-2 removed
23 unmodified lines24 #needs_sphinx = '1.0'25 26 # Add any Sphinx extension module names here, as strings. They can be extensions27 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.28-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.jsmath', 'sphinx.ext.viewcode']28+extensions = ['sphinx.ext.autodoc']29 30 # Add any paths that contain templates here, relative to this directory.31 templates_path = ['_templates']32 14 unmodified lines47 # |version| and |release|, also used in various other places throughout the48 # built documents.49 #50 # The short X.Y version.51-version = '0.3.2'51+version = '0.3.3'52 # The full version, including alpha/beta/rc tags.53 release = version54 55 # The language for content autogenerated by Sphinx. Refer to documentation177 unmodified linesmodified:requests/__init__.py+25 added
1 # -*- coding: utf-8 -*-2 3+import inspect4+5 import packages6 from core import *7 8 from core import __version__9+10+timeout = None11+12+class settings:13+ """Context manager for settings."""14+ 15+ cache = {}16+ 17+ def __init__(self, timeout):18+ self.module = inspect.getmodule(self)19+ 20+ # Cache settings21+ self.cache['timeout'] = self.module.timeout22+ 23+ self.module.timeout = timeout24+ 25+ def __enter__(self):26+ pass27+ 28+ def __exit__(self, type, value, traceback):29+ # Restore settings 30+ for key in self.cache:31+ setattr(self.module, key, self.cache[key])modified:requests/core.py+40 added-19 removed
10 unmodified lines11 """12 13 from __future__ import absolute_import14 15+import requests16 import urllib17 import urllib218+import socket19 import zlib20 21 from urllib2 import HTTPError22 from urlparse import urlparse1 unmodified line24 from .packages.poster.encode import multipart_encode25 from .packages.poster.streaminghttp import register_openers, get_handlers26 27 26-28 __title__ = 'requests'28-__version__ = '0.3.2'29-__build__ = 0x00030229+__version__ = '0.3.3'30+__build__ = 0x00030331 __author__ = 'Kenneth Reitz'32 __license__ = 'ISC'33 __copyright__ = 'Copyright 2011 Kenneth Reitz'34 3 unmodified lines38 'URLRequired', 'InvalidMethod', 'HTTPError'39 ]40 41 41-42 class _Request(urllib2.Request):43 """Hidden wrapper around the urllib2.Request object. Allows for manual44 setting of HTTP methods.45 """16 unmodified lines62 63 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')64 65 def __init__(self, url=None, headers=dict(), files=None, method=None,66- data=dict(), auth=None, cookiejar=None):66+ data=dict(), auth=None, cookiejar=None, timeout=None):67 68 self.url = url69 self.headers = headers70 self.files = files71 self.method = method72 self.data = data73 74+ socket.setdefaulttimeout(timeout)75+76+ for (k, v) in self.data.iteritems():77+ self.data[k] = v.encode('utf-8')78+79 # url encode data if it's a dict80 if hasattr(data, 'items'):76- self._enc_data = urllib.urlencode(data)81+ self._enc_data = urllib.urlencode(self.data)82 else:78- self._enc_data = data83+ self._enc_data = self.data84 85 self.response = Response()86 87 if isinstance(auth, (list, tuple)):71 unmodified lines159 pass160 161 self.response.url = getattr(resp, 'url', None)162 163+164 @staticmethod159- def _build_url(url, data):165+ def _build_url(url, data=None):166 """Build URLs."""167 168 if urlparse(url).query:169 return '%s&%s' % (url, data)2 unmodified lines172 return '%s?%s' % (url, data)173 else:174 return url175 176+177 def send(self, anyway=False):178 """Sends the request. Returns True of successful, false if not.179 If there was an HTTPError during transmission,180 self.response.status_code will contain the HTTPError code.25 unmodified lines206 if self.headers:207 req.headers.update(self.headers)208 209 if not self.sent or anyway:210+211+212+213 try:214 opener = self._get_opener()215 resp = opener(req)216 18 unmodified lines235 236 def read(self, *args):237 return self.response.read()238 239+240+241 class Response(object):242 """The :class:`Request` object. All :class:`Request` objects contain a243 :class:`Request.response <response>` attribute, which is an instance of244 this class.26 unmodified lines271 def read(self, *args):272 return self.content273 274 275+276 class AuthManager(object):277 """Authentication Manager."""278 279 def __new__(cls):28 unmodified lines308 pass309 310 self._auth[uri] = auth311 312+313 def add_password(self, realm, uri, user, passwd):314 """Adds password to AuthManager."""315 # uri could be a single URI or a sequence316 if isinstance(uri, basestring):139 unmodified lines456 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.457 :param cookies: (optional) CookieJar object to send with the :class:`Request`.458 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.459 :param auth: (optional) AuthObject to enable Basic HTTP Auth.460+ :param timeout: (optional) Float describing the timeout of the request.461 """462 data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())463 464 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),465 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),451- auth=kwargs.pop('auth', auth_manager.get_auth(url)))466+ auth=kwargs.pop('auth', auth_manager.get_auth(url)),467+ timeout=kwargs.pop('timeout', requests.timeout))468 r.send()469 470 return r.response471 472 457-def get(url, params={}, headers={}, cookies=None, auth=None):473+def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):474 """Sends a GET request. Returns :class:`Response` object.475 476 :param url: URL for the new :class:`Request` object.477 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.478 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.479 :param cookies: (optional) CookieJar object to send with the :class:`Request`.480 :param auth: (optional) AuthObject to enable Basic HTTP Auth.481+ :param timeout: (optional) Float describing the timeout of the request.482 """483 467- return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth)484+ return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)485 486 470-def head(url, params={}, headers={}, cookies=None, auth=None):487+def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):488 """Sends a HEAD request. Returns :class:`Response` object.489 490 :param url: URL for the new :class:`Request` object.491 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.492 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.493 :param cookies: (optional) CookieJar object to send with the :class:`Request`.494 :param auth: (optional) AuthObject to enable Basic HTTP Auth.495+ :param timeout: (optional) Float describing the timeout of the request.496 """497 480- return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth)498+ return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)499 500 483-def post(url, data={}, headers={}, files=None, cookies=None, auth=None):501+def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):502 """Sends a POST request. Returns :class:`Response` object.503 504 :param url: URL for the new :class:`Request` object.505 :param data: (optional) Dictionary of POST data to send with the :class:`Request`.506 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.507 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.508 :param cookies: (optional) CookieJar object to send with the :class:`Request`.509 :param auth: (optional) AuthObject to enable Basic HTTP Auth.510+ :param timeout: (optional) Float describing the timeout of the request.511 """512 494- return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth)513+ return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)514 515 497-def put(url, data='', headers={}, files={}, cookies=None, auth=None):516+def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):517 """Sends a PUT request. Returns :class:`Response` object.518 519 :param url: URL for the new :class:`Request` object.520 :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.521 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.522 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.523 :param cookies: (optional) CookieJar object to send with the :class:`Request`.524 :param auth: (optional) AuthObject to enable Basic HTTP Auth.525+ :param timeout: (optional) Float describing the timeout of the request.526 """527 508- return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth)528+ return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)529 530 511-def delete(url, params={}, headers={}, cookies=None, auth=None):531+def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):532 """Sends a DELETE request. Returns :class:`Response` object.533 534 :param url: URL for the new :class:`Request` object.535 :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.536 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.537 :param cookies: (optional) CookieJar object to send with the :class:`Request`.538 :param auth: (optional) AuthObject to enable Basic HTTP Auth.539+ :param timeout: (optional) Float describing the timeout of the request.540 """541 521- return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth)542+ return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)543 544 545 546 class RequestException(Exception):11 unmodified linesadded:requests/structures.py+360 added
1+2+# from: werkzeug3+4+class TypeConversionDict(dict):5+ """Works like a regular dict but the :meth:`get` method can perform6+ type conversions. :class:`MultiDict` and :class:`CombinedMultiDict`7+ are subclasses of this class and provide the same feature.8+ """9+10+ def get(self, key, default=None, type=None):11+ """Return the default value if the requested data doesn't exist.12+ If `type` is provided and is a callable it should convert the value,13+ return it or raise a :exc:`ValueError` if that is not possible. In14+ this case the function will return the default as if the value was not15+ found:16+17+ >>> d = TypeConversionDict(foo='42', bar='blub')18+ >>> d.get('foo', type=int)19+ 4220+ >>> d.get('bar', -1, type=int)21+ -122+23+ :param key: The key to be looked up.24+ :param default: The default value to be returned if the key can't25+ be looked up. If not further specified `None` is26+ returned.27+ :param type: A callable that is used to cast the value in the28+ :class:`MultiDict`. If a :exc:`ValueError` is raised29+ by this callable the default value is returned.30+ """31+ try:32+ rv = self[key]33+ if type is not None:34+ rv = type(rv)35+ except (KeyError, ValueError):36+ rv = default37+ return rv38+39+40+41+# from: werkzeug42+43+class MultiDict(TypeConversionDict):44+ """A :class:`MultiDict` is a dictionary subclass customized to deal with45+ multiple values for the same key which is for example used by the parsing46+ functions in the wrappers. This is necessary because some HTML form47+ elements pass multiple values for the same key.48+49+ :class:`MultiDict` implements all standard dictionary methods.50+ Internally, it saves all values for a key as a list, but the standard dict51+ access methods will only return the first value for a key. If you want to52+ gain access to the other values, too, you have to use the `list` methods as53+ explained below.54+55+ Basic Usage:56+57+ >>> d = MultiDict([('a', 'b'), ('a', 'c')])58+ >>> d59+ MultiDict([('a', 'b'), ('a', 'c')])60+ >>> d['a']61+ 'b'62+ >>> d.getlist('a')63+ ['b', 'c']64+ >>> 'a' in d65+ True66+67+ It behaves like a normal dict thus all dict functions will only return the68+ first value when multiple values for one key are found.69+70+ From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a71+ subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will72+ render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP73+ exceptions.74+75+ A :class:`MultiDict` can be constructed from an iterable of76+ ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.277+ onwards some keyword parameters.78+79+ :param mapping: the initial value for the :class:`MultiDict`. Either a80+ regular dict, an iterable of ``(key, value)`` tuples81+ or `None`.82+ """83+84+ # the key error this class raises. Because of circular dependencies85+ # with the http exception module this class is created at the end of86+ # this module.87+ KeyError = None88+89+ def __init__(self, mapping=None):90+ if isinstance(mapping, MultiDict):91+ dict.__init__(self, ((k, l[:]) for k, l in mapping.iterlists()))92+ elif isinstance(mapping, dict):93+ tmp = {}94+ for key, value in mapping.iteritems():95+ if isinstance(value, (tuple, list)):96+ value = list(value)97+ else:98+ value = [value]99+ tmp[key] = value100+ dict.__init__(self, tmp)101+ else:102+ tmp = {}103+ for key, value in mapping or ():104+ tmp.setdefault(key, []).append(value)105+ dict.__init__(self, tmp)106+107+ def __getstate__(self):108+ return dict(self.lists())109+110+ def __setstate__(self, value):111+ dict.clear(self)112+ dict.update(self, value)113+114+ def __iter__(self):115+ return self.iterkeys()116+117+ def __getitem__(self, key):118+ """Return the first data value for this key;119+ raises KeyError if not found.120+121+ :param key: The key to be looked up.122+ :raise KeyError: if the key does not exist.123+ """124+ if key in self:125+ return dict.__getitem__(self, key)[0]126+ raise self.KeyError(key)127+128+ def __setitem__(self, key, value):129+ """Like :meth:`add` but removes an existing key first.130+131+ :param key: the key for the value.132+ :param value: the value to set.133+ """134+ dict.__setitem__(self, key, [value])135+136+ def add(self, key, value):137+ """Adds a new value for the key.138+139+ .. versionadded:: 0.6140+141+ :param key: the key for the value.142+ :param value: the value to add.143+ """144+ dict.setdefault(self, key, []).append(value)145+146+ def getlist(self, key, type=None):147+ """Return the list of items for a given key. If that key is not in the148+ `MultiDict`, the return value will be an empty list. Just as `get`149+ `getlist` accepts a `type` parameter. All items will be converted150+ with the callable defined there.151+152+ :param key: The key to be looked up.153+ :param type: A callable that is used to cast the value in the154+ :class:`MultiDict`. If a :exc:`ValueError` is raised155+ by this callable the value will be removed from the list.156+ :return: a :class:`list` of all the values for the key.157+ """158+ try:159+ rv = dict.__getitem__(self, key)160+ except KeyError:161+ return []162+ if type is None:163+ return list(rv)164+ result = []165+ for item in rv:166+ try:167+ result.append(type(item))168+ except ValueError:169+ pass170+ return result171+172+ def setlist(self, key, new_list):173+ """Remove the old values for a key and add new ones. Note that the list174+ you pass the values in will be shallow-copied before it is inserted in175+ the dictionary.176+177+ >>> d = MultiDict()178+ >>> d.setlist('foo', ['1', '2'])179+ >>> d['foo']180+ '1'181+ >>> d.getlist('foo')182+ ['1', '2']183+184+ :param key: The key for which the values are set.185+ :param new_list: An iterable with the new values for the key. Old values186+ are removed first.187+ """188+ dict.__setitem__(self, key, list(new_list))189+190+ def setdefault(self, key, default=None):191+ """Returns the value for the key if it is in the dict, otherwise it192+ returns `default` and sets that value for `key`.193+194+ :param key: The key to be looked up.195+ :param default: The default value to be returned if the key is not196+ in the dict. If not further specified it's `None`.197+ """198+ if key not in self:199+ self[key] = default200+ else:201+ default = self[key]202+ return default203+204+ def setlistdefault(self, key, default_list=None):205+ """Like `setdefault` but sets multiple values. The list returned206+ is not a copy, but the list that is actually used internally. This207+ means that you can put new values into the dict by appending items208+ to the list:209+210+ >>> d = MultiDict({"foo": 1})211+ >>> d.setlistdefault("foo").extend([2, 3])212+ >>> d.getlist("foo")213+ [1, 2, 3]214+215+ :param key: The key to be looked up.216+ :param default: An iterable of default values. It is either copied217+ (in case it was a list) or converted into a list218+ before returned.219+ :return: a :class:`list`220+ """221+ if key not in self:222+ default_list = list(default_list or ())223+ dict.__setitem__(self, key, default_list)224+ else:225+ default_list = dict.__getitem__(self, key)226+ return default_list227+228+ def items(self, multi=False):229+ """Return a list of ``(key, value)`` pairs.230+231+ :param multi: If set to `True` the list returned will have a232+ pair for each value of each key. Otherwise it233+ will only contain pairs for the first value of234+ each key.235+236+ :return: a :class:`list`237+ """238+ return list(self.iteritems(multi))239+240+ def lists(self):241+ """Return a list of ``(key, values)`` pairs, where values is the list of242+ all values associated with the key.243+244+ :return: a :class:`list`245+ """246+ return list(self.iterlists())247+248+ def values(self):249+ """Returns a list of the first value on every key's value list.250+251+ :return: a :class:`list`.252+ """253+ return [self[key] for key in self.iterkeys()]254+255+ def listvalues(self):256+ """Return a list of all values associated with a key. Zipping257+ :meth:`keys` and this is the same as calling :meth:`lists`:258+259+ >>> d = MultiDict({"foo": [1, 2, 3]})260+ >>> zip(d.keys(), d.listvalues()) == d.lists()261+ True262+263+ :return: a :class:`list`264+ """265+ return list(self.iterlistvalues())266+267+ def iteritems(self, multi=False):268+ """Like :meth:`items` but returns an iterator."""269+ for key, values in dict.iteritems(self):270+ if multi:271+ for value in values:272+ yield key, value273+ else:274+ yield key, values[0]275+276+ def iterlists(self):277+ """Like :meth:`items` but returns an iterator."""278+ for key, values in dict.iteritems(self):279+ yield key, list(values)280+281+ def itervalues(self):282+ """Like :meth:`values` but returns an iterator."""283+ for values in dict.itervalues(self):284+ yield values[0]285+286+ def iterlistvalues(self):287+ """Like :meth:`listvalues` but returns an iterator."""288+ return dict.itervalues(self)289+290+ def copy(self):291+ """Return a shallow copy of this object."""292+ return self.__class__(self)293+294+ def to_dict(self, flat=True):295+ """Return the contents as regular dict. If `flat` is `True` the296+ returned dict will only have the first item present, if `flat` is297+ `False` all values will be returned as lists.298+299+ :param flat: If set to `False` the dict returned will have lists300+ with all the values in it. Otherwise it will only301+ contain the first value for each key.302+ :return: a :class:`dict`303+ """304+ if flat:305+ return dict(self.iteritems())306+ return dict(self.lists())307+308+ def update(self, other_dict):309+ """update() extends rather than replaces existing key lists."""310+ for key, value in iter_multi_items(other_dict):311+ MultiDict.add(self, key, value)312+313+ def pop(self, key, default=_missing):314+ """Pop the first item for a list on the dict. Afterwards the315+ key is removed from the dict, so additional values are discarded:316+317+ >>> d = MultiDict({"foo": [1, 2, 3]})318+ >>> d.pop("foo")319+ 1320+ >>> "foo" in d321+ False322+323+ :param key: the key to pop.324+ :param default: if provided the value to return if the key was325+ not in the dictionary.326+ """327+ try:328+ return dict.pop(self, key)[0]329+ except KeyError, e:330+ if default is not _missing:331+ return default332+ raise self.KeyError(str(e))333+334+ def popitem(self):335+ """Pop an item from the dict."""336+ try:337+ item = dict.popitem(self)338+ return (item[0], item[1][0])339+ except KeyError, e:340+ raise self.KeyError(str(e))341+342+ def poplist(self, key):343+ """Pop the list for a key from the dict. If the key is not in the dict344+ an empty list is returned.345+346+ .. versionchanged:: 0.5347+ If the key does no longer exist a list is returned instead of348+ raising an error.349+ """350+ return dict.pop(self, key, [])351+352+ def popitemlist(self):353+ """Pop a ``(key, list)`` tuple from the dict."""354+ try:355+ return dict.popitem(self)356+ except KeyError, e:357+ raise self.KeyError(str(e))358+359+ def __repr__(self):360+ return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))modified:AUTHORS+1 added
15 unmodified lines16 - Dj Gilcrease17 - Justin Murphy18 - Rob Madole19 - Aram Dulyan20+- Johannes Gorsetmodified:HISTORY.rst+8 added
1 History2 -------3 4+0.3.3 (2011-05-12)5+++++++++++++++++++6+7+* Request timeouts8+* Unicode url-encoded data9+* Settings context manager and module10+11+12 0.3.2 (2011-04-15)13 ++++++++++++++++++14 15 * Automatic Decompression of GZip Encoded Content68 unmodified linesmodified:README.rst+10 added-10 removed
61 unmodified lines62 If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.63 If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.64 65 GET Requests66- >>> request.get(url, params={}, headers={}, cookies=None, auth=None)67- <request object>66+ >>> requests.get(url, params={}, headers={}, cookies=None, auth=None)67+ <Response [200]>68 69 HEAD Requests70- >>> request.head(url, params={}, headers={}, cookies=None, auth=None)71- <request object>70+ >>> requests.head(url, params={}, headers={}, cookies=None, auth=None)71+ <Response [200]>72 73 PUT Requests74- >>> request.put(url, data='', headers={}, files={}, cookies=None, auth=None)75- <request object>74+ >>> requests.put(url, data='', headers={}, files={}, cookies=None, auth=None)75+ <Response [200]>76 77 POST Requests78- >>> request.post(url, data={}, headers={}, files={}, cookies=None, auth=None)79- <request object>78+ >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None)79+ <Response [200]>80 81 DELETE Requests82- >>> request.delete(url, params={}, headers={}, cookies=None, auth=None)83- <request object>82+ >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None)83+ <Response [200]>84 85 86 **Responses:**87 65 unmodified linesmodified:test_requests.py+6 added
137 unmodified lines138 139 r = requests.get('https://convore.com/api/account/verify.json')140 self.assertEquals(r.status_code, 200)141 142+ def test_unicode_get(self):143+ requests.get('http://google.com', params={'foo': u'føø'})144+ requests.get('http://google.com', params={'foo': u'foo'})145+ requests.get('http://google.com/ø', params={'foo': u'foo'})146+147+148 if __name__ == '__main__':149 unittest.main()