Skip to content
Myr

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

8 files+452 added−31 removed

modified:docs/conf.py+2 added-2 removed
23 unmodified lines
24#needs_sphinx = '1.0'2526# Add any Sphinx extension module names here, as strings. They can be extensions27# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.28extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.jsmath', 'sphinx.ext.viewcode']28extensions = ['sphinx.ext.autodoc']2930# Add any paths that contain templates here, relative to this directory.31templates_path = ['_templates']32
14 unmodified lines
47# |version| and |release|, also used in various other places throughout the48# built documents.49#50# The short X.Y version.51version = '0.3.2'51version = '0.3.3'52# The full version, including alpha/beta/rc tags.53release = version5455# The language for content autogenerated by Sphinx. Refer to documentation
177 unmodified lines
modified:requests/__init__.py+25 added
1# -*- coding: utf-8 -*-23import inspect45import packages6from core import *78from core import __version__910timeout = None1112class 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 lines
11"""1213from __future__ import absolute_import1415import requests16import urllib17import urllib218import socket19import zlib2021from urllib2 import HTTPError22from urlparse import urlparse
1 unmodified line
24from .packages.poster.encode import multipart_encode25from .packages.poster.streaminghttp import register_openers, get_handlers26272628__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 lines
38 'URLRequired', 'InvalidMethod', 'HTTPError'39]40414142class _Request(urllib2.Request):43 """Hidden wrapper around the urllib2.Request object. Allows for manual44 setting of HTTP methods.45 """
16 unmodified lines
6263 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')6465 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):6768 self.url = url69 self.headers = headers70 self.files = files71 self.method = method72 self.data = data7374 socket.setdefaulttimeout(timeout)7576 for (k, v) in self.data.iteritems():77 self.data[k] = v.encode('utf-8')7879 # 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.data8485 self.response = Response()8687 if isinstance(auth, (list, tuple)):
71 unmodified lines
159 pass160161 self.response.url = getattr(resp, 'url', None)162163164 @staticmethod159 def _build_url(url, data):165 def _build_url(url, data=None):166 """Build URLs."""167168 if urlparse(url).query:169 return '%s&%s' % (url, data)
2 unmodified lines
172 return '%s?%s' % (url, data)173 else:174 return url175176177 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 lines
206 if self.headers:207 req.headers.update(self.headers)208209 if not self.sent or anyway:210211212213 try:214 opener = self._get_opener()215 resp = opener(req)216
18 unmodified lines
235236 def read(self, *args):237 return self.response.read()238239240241class 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 lines
271 def read(self, *args):272 return self.content273274275276class AuthManager(object):277 """Authentication Manager."""278279 def __new__(cls):
28 unmodified lines
308 pass309310 self._auth[uri] = auth311312313 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 lines
456 :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())463464 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()469470 return r.response471472457def get(url, params={}, headers={}, cookies=None, auth=None):473def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):474 """Sends a GET request. Returns :class:`Response` object.475476 :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 """483467 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)485486470def head(url, params={}, headers={}, cookies=None, auth=None):487def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):488 """Sends a HEAD request. Returns :class:`Response` object.489490 :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 """497480 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)499500483def post(url, data={}, headers={}, files=None, cookies=None, auth=None):501def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):502 """Sends a POST request. Returns :class:`Response` object.503504 :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 """512494 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)514515497def put(url, data='', headers={}, files={}, cookies=None, auth=None):516def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):517 """Sends a PUT request. Returns :class:`Response` object.518519 :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 """527508 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)529530511def delete(url, params={}, headers={}, cookies=None, auth=None):531def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):532 """Sends a DELETE request. Returns :class:`Response` object.533534 :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 """541521 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)543544545546class RequestException(Exception):
11 unmodified lines
added:requests/structures.py+360 added
12# from: werkzeug34class 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 """910 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:1617 >>> d = TypeConversionDict(foo='42', bar='blub')18 >>> d.get('foo', type=int)19 4220 >>> d.get('bar', -1, type=int)21 -12223 :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 rv38394041# from: werkzeug4243class 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.4849 :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.5455 Basic Usage:5657 >>> 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 True6667 It behaves like a normal dict thus all dict functions will only return the68 first value when multiple values for one key are found.6970 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.7475 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.7879 :param mapping: the initial value for the :class:`MultiDict`. Either a80 regular dict, an iterable of ``(key, value)`` tuples81 or `None`.82 """8384 # 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 = None8889 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)106107 def __getstate__(self):108 return dict(self.lists())109110 def __setstate__(self, value):111 dict.clear(self)112 dict.update(self, value)113114 def __iter__(self):115 return self.iterkeys()116117 def __getitem__(self, key):118 """Return the first data value for this key;119 raises KeyError if not found.120121 :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)127128 def __setitem__(self, key, value):129 """Like :meth:`add` but removes an existing key first.130131 :param key: the key for the value.132 :param value: the value to set.133 """134 dict.__setitem__(self, key, [value])135136 def add(self, key, value):137 """Adds a new value for the key.138139 .. versionadded:: 0.6140141 :param key: the key for the value.142 :param value: the value to add.143 """144 dict.setdefault(self, key, []).append(value)145146 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.151152 :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 result171172 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.176177 >>> d = MultiDict()178 >>> d.setlist('foo', ['1', '2'])179 >>> d['foo']180 '1'181 >>> d.getlist('foo')182 ['1', '2']183184 :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))189190 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`.193194 :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 default203204 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:209210 >>> d = MultiDict({"foo": 1})211 >>> d.setlistdefault("foo").extend([2, 3])212 >>> d.getlist("foo")213 [1, 2, 3]214215 :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_list227228 def items(self, multi=False):229 """Return a list of ``(key, value)`` pairs.230231 :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.235236 :return: a :class:`list`237 """238 return list(self.iteritems(multi))239240 def lists(self):241 """Return a list of ``(key, values)`` pairs, where values is the list of242 all values associated with the key.243244 :return: a :class:`list`245 """246 return list(self.iterlists())247248 def values(self):249 """Returns a list of the first value on every key's value list.250251 :return: a :class:`list`.252 """253 return [self[key] for key in self.iterkeys()]254255 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`:258259 >>> d = MultiDict({"foo": [1, 2, 3]})260 >>> zip(d.keys(), d.listvalues()) == d.lists()261 True262263 :return: a :class:`list`264 """265 return list(self.iterlistvalues())266267 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]275276 def iterlists(self):277 """Like :meth:`items` but returns an iterator."""278 for key, values in dict.iteritems(self):279 yield key, list(values)280281 def itervalues(self):282 """Like :meth:`values` but returns an iterator."""283 for values in dict.itervalues(self):284 yield values[0]285286 def iterlistvalues(self):287 """Like :meth:`listvalues` but returns an iterator."""288 return dict.itervalues(self)289290 def copy(self):291 """Return a shallow copy of this object."""292 return self.__class__(self)293294 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.298299 :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())307308 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)312313 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:316317 >>> d = MultiDict({"foo": [1, 2, 3]})318 >>> d.pop("foo")319 1320 >>> "foo" in d321 False322323 :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))333334 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))341342 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.345346 .. 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, [])351352 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))358359 def __repr__(self):360 return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))
modified:AUTHORS+1 added
15 unmodified lines
16- Dj Gilcrease17- Justin Murphy18- Rob Madole19- Aram Dulyan20- Johannes Gorset
modified:HISTORY.rst+8 added
1History2-------340.3.3 (2011-05-12)5++++++++++++++++++67* Request timeouts8* Unicode url-encoded data9* Settings context manager and module1011120.3.2 (2011-04-15)13++++++++++++++++++1415* Automatic Decompression of GZip Encoded Content
68 unmodified lines
modified:README.rst+10 added-10 removed
61 unmodified lines
62If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.63If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.6465 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]>6869 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]>7273 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]>7677 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]>8081 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]>848586**Responses:**87
65 unmodified lines
modified:test_requests.py+6 added
137 unmodified lines
138139 r = requests.get('https://convore.com/api/account/verify.json')140 self.assertEquals(r.status_code, 200)141142 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'})146147148if __name__ == '__main__':149 unittest.main()