Merge branch 'release/0.4.0'
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 0c00a17, 51360e1 · Browse files · 7 files·+124 added−373 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+124 added−373 removed
- other:+124 added−373 removed
Provenance
- Commit
aa33194- Tree
a646bd1- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
0c00a17- Parent 2
51360e1
7 files changed+124 added−373 removed
modified:requests/async.py-7 removed
37 unmodified lines38 raise ImportError('No Async adaptations of urllib2 found!')39 40 41 from .core import *42-43-44-__all__ = [45- 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 46- 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError', 47- 'URLRequired', 'InvalidMethod', 'HTTPError'48-]modified:requests/core.py+5 added-4 removed
10 unmodified lines11 12 """13 14 __title__ = 'requests'15-__version__ = '0.3.4'16-__build__ = 0x00030415+__version__ = '0.4.0'16+__build__ = 0x00040017 __author__ = 'Kenneth Reitz'18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 21 22+22-from .models import HTTPError, auth_manager23-from .api import *23+from models import HTTPError, auth_manager24+from api import *modified:requests/models.py+57 added-20 removed
13 unmodified lines14 15 from urllib2 import HTTPError16 from urlparse import urlparse17 18-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler19-18+from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19+from .structures import CaseInsensitiveDict20 from .packages.poster.encode import multipart_encode21 from .packages.poster.streaminghttp import register_openers, get_handlers22 23 5 unmodified lines29 30 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')31 32 def __init__(self, url=None, headers=dict(), files=None, method=None,33- data=dict(), auth=None, cookiejar=None, timeout=None):33+ data=dict(), auth=None, cookiejar=None, timeout=None, redirect=True):34 35 socket.setdefaulttimeout(timeout)36 37 self.url = url38 self.headers = headers39 self.files = files40 self.method = method41- self.data = {}41+ self.data = dict()42+ self.redirect = redirect43 44 # self.data = {}45 if hasattr(data, 'items'):46 for (k, v) in data.items():54 unmodified lines101 auth_manager.add_auth(self.url, self.auth)102 103 _handlers.append(self.auth.handler)104 105+106+ _handlers.append(HTTPRedirectHandler)107+ # print _handlers108+ # print '^^'109+ # print '!'110+111 if not _handlers:112 return urllib2.urlopen113 114+ if self.data or self.files:107- _handlers.extend(get_handlers())115+ _handlers.extend(get_handlers())116+117 opener = urllib2.build_opener(*_handlers)118 119 if self.headers:120 # Allow default headers in the opener to be overloaded7 unmodified lines128 return opener.open129 130 def _build_response(self, resp):131 """Build internal Response object from given response."""123- if isinstance(resp, HTTPError):124- # print resp.__dict__125- pass132 127- self.response.status_code = getattr(resp, 'code', None)133+ def build(resp):134 129- try:130- self.response.headers = getattr(resp.info(), 'dict', None)131- self.response.content = resp.read()132- except AttributeError, why:133- pass135+ response = Response()136+ response.status_code = getattr(resp, 'code', None)137 135- if self.response.headers.get('content-encoding', None) == 'gzip':138 try:137- self.response.content = zlib.decompress(self.response.content, 16+zlib.MAX_WBITS)138- except zlib.error:139+ response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))140+ response.content = resp.read()141+ except AttributeError:142 pass143 141- self.response.url = getattr(resp, 'url', None)144+ if response.headers['content-encoding'] == 'gzip':145+ try:146+ response.content = zlib.decompress(response.content, 16+zlib.MAX_WBITS)147+ except zlib.error:148+ pass149 150+ response.url = getattr(resp, 'url', None)151 152+ return response153+154+155+ history = []156+157+ r = build(resp)158+159+ if self.redirect:160+161+ while 'location' in r.headers:162+163+ history.append(r)164+165+ url = r.headers['location']166+167+ request = Request(168+ url, self.headers, self.files, self.method,169+ self.data, self.auth, self.cookiejar, redirect=False170+ )171+ request.send()172+ r = request.response173+174+ r.history = history175+176+ self.response = r177+178+179 @staticmethod180 def _build_url(url, data=None):181 """Build URLs."""182 48 unmodified lines231 self.cookiejar.extract_cookies(resp, req)232 233 except urllib2.HTTPError, why:234 self._build_response(why)235+ if not self.redirect:200- self.response.error = why236+ self.response.error = why237 else:238 self._build_response(resp)239 self.response.ok = True240 19 unmodified lines260 261 def __init__(self):262 self.content = None263 self.status_code = None228- self.headers = dict()264+ self.headers = CaseInsensitiveDict()265 self.url = None266 self.ok = False267 self.error = None268 self.cached = False269+ self.history = []270 271 272 def __repr__(self):273 return '<Response [%s]>' % (self.status_code)199 unmodified linesmodified:requests/monkeys.py+13 added-3 removed
1-# -*- coding: utf-8 -*-1+#-*- coding: utf-8 -*-2 3 """4 requests.monkeys5 ~~~~~~~~~~~~~~~~20 unmodified lines26 27 return urllib2.Request.get_method(self)28 29 30+class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31+32+ def http_error_301(self, req, fp, code, msg, headers):33+ pass34+35+ http_error_302 = http_error_303 = http_error_307 = http_error_30136+37+38+39 class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):31- # from mercurial40 41 def __init__(self, *args, **kwargs):42 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)43 self.retried_req = None8 unmodified lines52 # Reset the retry counter once for each request.53 if req is not self.retried_req:54 self.retried_req = req55 self.retried = 056+57 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(49- self, auth_header, host, req, headers)58+ self, auth_header, host, req, headers59+ )60 61 62 63 class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):28 unmodified linesmodified:requests/structures.py+34 added-333 removed
1+# -*- coding: utf-8 -*-2 2-# from: werkzeug3+"""4+requests.structures5+~~~~~~~~~~~~~~~~~~~6 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- """7+Datastructures that power Requests.8 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:9+"""10 17- >>> d = TypeConversionDict(foo='42', bar='blub')18- >>> d.get('foo', type=int)19- 4220- >>> d.get('bar', -1, type=int)21- -111+from UserDict import DictMixin12 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 rv13 14+class CaseInsensitiveDict(DictMixin):15+ """docstring for CaseInsensitiveDict"""16 17+ def __init__(self, *args, **kwargs):18+ # super(CaseInsensitiveDict, self).__init__()19+ self.data = dict(*args, **kwargs)20 41-# from: werkzeug21+ def __repr__(self):22+ return self.data.__repr__()23 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.24+ def __getstate__(self):25+ return self.data.copy()26 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.27+ def __setstate__(self, d):28+ self.data = d29 55- Basic Usage:30+ def _lower_keys(self):31+ return map(str.lower, self.data.keys())32 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- True33 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.34+ def __contains__(self, key):35+ return key.lower() in self._lower_keys()36 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.37 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-38 def __getitem__(self, key):118- """Return the first data value for this key;119- raises KeyError if not found.39 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)40+ if key.lower() in self:41+ return self.items()[self._lower_keys().index(key.lower())][1]42 43+44 def __setitem__(self, key, value):129- """Like :meth:`add` but removes an existing key first.45+ return self.data.__setitem__(key, value)46 131- :param key: the key for the value.132- :param value: the value to set.133- """134- dict.__setitem__(self, key, [value])47 136- def add(self, key, value):137- """Adds a new value for the key.48+ def __delitem__(self, key):49+ return self.data.__delitem__(key)50 139- .. versionadded:: 0.651 141- :param key: the key for the value.142- :param value: the value to add.143- """144- dict.setdefault(self, key, []).append(value)52+ def __keys__(self):53+ return self.data.__keys__()54 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.55 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 result56+ def __iter__(self):57+ return self.data.__iter__()58 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.59 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))60+ def iteritems(self):61+ return self.data.iteritems()modified:HISTORY.rst+10 added-2 removed
1 History2 -------3 4-0.3.45-+++++4+0.4.0 (2011-05-15)5+++++++++++++++++++6 7+* Response.history: list of redirected responses8+* Case-Insensitive Header Dictionaries!9+* Unicode URLs10+11+12+0.3.4 (2011-05-14)13+++++++++++++++++++14+15 * Urllib2 HTTPAuthentication Recursion fix (Basic/Digest)16 * Internal Refactor17 * Bytes data upload Bugfix18 82 unmodified linesmodified:README.rst+5 added-4 removed
13 unmodified lines14 + Simple HTTP Header Request Attachment15 + Simple Data/Params Request Attachment16 + Simple Multipart File Uploads17 + CookieJar Support18+ + Redirection History19+ + Redirection Recursion Urllib Fix20+ + Auto Decompression of GZipped Content21+ + Unicode URL Support22 23 - Simple Authentication24 + Simple URL + HTTP Auth Registry25 120 unmodified lines146 147 Roadmap148 -------149 146-- Sphinx Documentation (http://code.kennethreitz.com/requests/)147-- Exhaustive unit tests148-- Get rid of Poster (gets really nasty in py3.x)149-- Python 3.x Support150+- Sphinx Documentation151 152 .. _`the repository`: http://github.com/kennethreitz/requests153 .. _AUTHORS: http://github.com/kennethreitz/requests/blob/master/AUTHORS