Skip to content
Myr

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

7 files+124 added−373 removed

modified:requests/async.py-7 removed
37 unmodified lines
38 raise ImportError('No Async adaptations of urllib2 found!')394041from .core import *424344__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 lines
1112"""1314__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'20212222from .models import HTTPError, auth_manager23from .api import *23from models import HTTPError, auth_manager24from api import *
modified:requests/models.py+57 added-20 removed
13 unmodified lines
1415from urllib2 import HTTPError16from urlparse import urlparse1718from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler1918from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19from .structures import CaseInsensitiveDict20from .packages.poster.encode import multipart_encode21from .packages.poster.streaminghttp import register_openers, get_handlers2223
5 unmodified lines
2930 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')3132 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):3435 socket.setdefaulttimeout(timeout)3637 self.url = url38 self.headers = headers39 self.files = files40 self.method = method41 self.data = {}41 self.data = dict()42 self.redirect = redirect4344 # self.data = {}45 if hasattr(data, 'items'):46 for (k, v) in data.items():
54 unmodified lines
101 auth_manager.add_auth(self.url, self.auth)102103 _handlers.append(self.auth.handler)104105106 _handlers.append(HTTPRedirectHandler)107 # print _handlers108 # print '^^'109 # print '!'110111 if not _handlers:112 return urllib2.urlopen113114 if self.data or self.files:107 _handlers.extend(get_handlers())115 _handlers.extend(get_handlers())116117 opener = urllib2.build_opener(*_handlers)118119 if self.headers:120 # Allow default headers in the opener to be overloaded
7 unmodified lines
128 return opener.open129130 def _build_response(self, resp):131 """Build internal Response object from given response."""123 if isinstance(resp, HTTPError):124 # print resp.__dict__125 pass132127 self.response.status_code = getattr(resp, 'code', None)133 def build(resp):134129 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)137135 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 pass143141 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 pass149150 response.url = getattr(resp, 'url', None)151152 return response153154155 history = []156157 r = build(resp)158159 if self.redirect:160161 while 'location' in r.headers:162163 history.append(r)164165 url = r.headers['location']166167 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.response173174 r.history = history175176 self.response = r177178179 @staticmethod180 def _build_url(url, data=None):181 """Build URLs."""182
48 unmodified lines
231 self.cookiejar.extract_cookies(resp, req)232233 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 lines
260261 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 = []270271272 def __repr__(self):273 return '<Response [%s]>' % (self.status_code)
199 unmodified lines
modified:requests/monkeys.py+13 added-3 removed
1# -*- coding: utf-8 -*-1#-*- coding: utf-8 -*-23"""4requests.monkeys5~~~~~~~~~~~~~~~~
20 unmodified lines
2627 return urllib2.Request.get_method(self)282930class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):3132 def http_error_301(self, req, fp, code, msg, headers):33 pass3435 http_error_302 = http_error_303 = http_error_307 = http_error_30136373839class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):31 # from mercurial4041 def __init__(self, *args, **kwargs):42 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)43 self.retried_req = None
8 unmodified lines
52 # Reset the retry counter once for each request.53 if req is not self.retried_req:54 self.retried_req = req55 self.retried = 05657 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(49 self, auth_header, host, req, headers)58 self, auth_header, host, req, headers59 )60616263class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
28 unmodified lines
modified:requests/structures.py+34 added-333 removed
1# -*- coding: utf-8 -*-22# from: werkzeug3"""4requests.structures5~~~~~~~~~~~~~~~~~~~64class 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 """7Datastructures that power Requests.810 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"""1017 >>> d = TypeConversionDict(foo='42', bar='blub')18 >>> d.get('foo', type=int)19 4220 >>> d.get('bar', -1, type=int)21 -111from UserDict import DictMixin1223 :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 rv1314class CaseInsensitiveDict(DictMixin):15 """docstring for CaseInsensitiveDict"""1617 def __init__(self, *args, **kwargs):18 # super(CaseInsensitiveDict, self).__init__()19 self.data = dict(*args, **kwargs)2041# from: werkzeug21 def __repr__(self):22 return self.data.__repr__()2343class 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()2649 :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 = d2955 Basic Usage:30 def _lower_keys(self):31 return map(str.lower, self.data.keys())3257 >>> 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 True3367 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()3670 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.3775 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()11638 def __getitem__(self, key):118 """Return the first data value for this key;119 raises KeyError if not found.39121 :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]424344 def __setitem__(self, key, value):129 """Like :meth:`add` but removes an existing key first.45 return self.data.__setitem__(key, value)46131 :param key: the key for the value.132 :param value: the value to set.133 """134 dict.__setitem__(self, key, [value])47136 def add(self, key, value):137 """Adds a new value for the key.48 def __delitem__(self, key):49 return self.data.__delitem__(key)50139 .. versionadded:: 0.651141 :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__()54146 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.55152 :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__()58172 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.59177 >>> 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))60 def iteritems(self):61 return self.data.iteritems()
modified:HISTORY.rst+10 added-2 removed
1History2-------340.3.45+++++40.4.0 (2011-05-15)5++++++++++++++++++67* Response.history: list of redirected responses8* Case-Insensitive Header Dictionaries!9* Unicode URLs1011120.3.4 (2011-05-14)13++++++++++++++++++1415* Urllib2 HTTPAuthentication Recursion fix (Basic/Digest)16* Internal Refactor17* Bytes data upload Bugfix18
82 unmodified lines
modified:README.rst+5 added-4 removed
13 unmodified lines
14 + 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 Support2223- Simple Authentication24 + Simple URL + HTTP Auth Registry25
120 unmodified lines
146147Roadmap148-------149146- 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 Documentation151152.. _`the repository`: http://github.com/kennethreitz/requests153.. _AUTHORS: http://github.com/kennethreitz/requests/blob/master/AUTHORS