Merge branch 'develop' into urlencode
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jérémy Bethmont · committed by Jérémy Bethmont · parents 0b6dc09, e1714e6 · Browse files · 16 files·+235 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+235 added−30 removed
- other:+235 added−30 removed
Provenance
- Commit
7dc581f- Tree
2f03060- Author
Jérémy Bethmont <jeremy.bethmont@gmail.com>- Committer
Jérémy Bethmont <jeremy.bethmont@gmail.com>- Parent 1
0b6dc09- Parent 2
e1714e6
16 files changed+235 added−30 removed
added:debian/changelog+5 added
1+python-requests (0.4.1-0) testing; urgency=low2+3+ * Initial Debian package4+5+ -- Bruno Clermont <bruno.clermont@gmail.com> Thu, 26 May 2011 16:25:00 -0500added:debian/compat+1 added
1+5added:debian/control+13 added
1+Source: python-requests2+Section: python3+Priority: optional4+Maintainer: Bruno Clermont <bruno.clermont@gmail.com>5+Homepage: https://github.com/bclermont/requests6+Bugs: https://github.com/bclermont/requests/issues7+Build-Depends: debhelper, python-support8+9+Package: python-requests10+Architecture: all11+Depends: ${python:Depends}, python-support12+Provides: ${python:Provides}13+Description: Python HTTP Requests for Humans.added:debian/docs+1 added
1+docs/user/*.rstadded:debian/pyversions+1 added
1+2.4-added:debian/rules+42 added
1+#!/usr/bin/make -f2+3+# Verbose mode4+#export DH_VERBOSE=15+6+clean:7+ dh_testdir8+ dh_testroot9+10+ rm -rf build requests.egg-info11+# find django-sentry/ -name *.pyc | xargs rm -f12+13+ dh_clean14+15+build:16+ dh_testdir17+18+ python setup.py build19+20+install:21+ dh_testdir22+ dh_installdirs23+24+ python setup.py install --root $(CURDIR)/debian/python-requests25+26+binary-indep: install27+28+binary-arch: install29+ dh_install30+ dh_installdocs31+# dh_installchangelogs32+ dh_compress33+ dh_fixperms34+ dh_pysupport35+ dh_gencontrol36+ dh_installdeb37+ dh_md5sums38+ dh_builddeb -- -Z lzma -z939+40+binary: binary-indep binary-arch41+.PHONY: build clean binary-indep binary-arch binary42+modified:requests/config.py+3 added-1 removed
51 unmodified lines52 except AttributeError:53 return None54 return object.__getattribute__(self, key)55 56-settings = Settings()56+settings = Settings()57+settings.base_headers = {'User-Agent': 'python-requests.org'}58+settings.accept_gzip = Truemodified:requests/core.py+2 added-2 removed
10 unmodified lines11 12 """13 14 __title__ = 'requests'15-__version__ = '0.5.0'16-__build__ = 0x00050015+__version__ = '0.5.1'16+__build__ = 0x00050117 __author__ = 'Kenneth Reitz'18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 5 unmodified linesmodified:requests/models.py+29 added-13 removed
14 unmodified lines15 from urlparse import urlparse, urlunparse16 from datetime import datetime17 18 from .config import settings19-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19+from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20 from .structures import CaseInsensitiveDict21 from .packages.poster.encode import multipart_encode22 from .packages.poster.streaminghttp import register_openers, get_handlers23 from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod56 unmodified lines80 #: True if Request has been sent.81 self.sent = False82 83 84+ # Header manipulation and defaults.85+86+ if settings.accept_gzip:87+ settings.base_headers.update({'Accept-Encoding': 'gzip'})88+89+ if headers:90+ headers = CaseInsensitiveDict(self.headers)91+ else:92+ headers = CaseInsensitiveDict()93+94+ for (k, v) in settings.base_headers.items():95+ if k not in headers:96+ headers[k] = v97+98+ self.headers = headers99+100+101 def __repr__(self):102 return '<Request [%s]>' % (self.method)103 104 76 unmodified lines181 history = []182 183 r = build(resp)184 168- if r.status_code in REDIRECT_STATI:169- self.redirect = True185+ if r.status_code in REDIRECT_STATI and not self.redirect:186 171- if self.redirect:172-187 while (188 ('location' in r.headers) and189 ((self.method in ('GET', 'HEAD')) or190 (r.status_code is 303) or33 unmodified lines224 def _encode_params(data):225 """Encode parameters in a piece of data.226 227 If the data supplied is a dictionary, encodes each parameter in it, and214- returns the dictionary of encoded parameters, and a urlencoded version215- of that.228+ returns a list of tuples containing the encoded parameters, and a urlencoded229+ version of that.230 231 Otherwise, assumes the data is already encoded appropriately, and232 returns it twice.233 234 """235 if hasattr(data, 'items'):222- result = {}223- for (k, v) in data.items():224- result[k.encode('utf-8') if isinstance(k, unicode) else k] \225- = v.encode('utf-8') if isinstance(v, unicode) else v236+ result = []237+ for k, vs in data.items():238+ for v in isinstance(vs, list) and vs or [vs]:239+ result.append((k.encode('utf-8') if isinstance(k, unicode) else k,240+ v.encode('utf-8') if isinstance(v, unicode) else v))241 return result, urllib.urlencode(result, doseq=True)242 else:243 return data, data244 304 unmodified lines549 """550 551 _handlers = {552 'basic': HTTPBasicAuthHandler,553+ 'forced_basic': HTTPForcedBasicAuthHandler,554 'digest': HTTPDigestAuthHandler,555 'proxy_basic': urllib2.ProxyBasicAuthHandler,556 'proxy_digest': urllib2.ProxyDigestAuthHandler557 }558 543- def __init__(self, username, password, handler='basic', realm=None):559+ def __init__(self, username, password, handler='forced_basic', realm=None):560 self.username = username561 self.password = password562 self.realm = realm563 564 if isinstance(handler, basestring):549- self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)565+ self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)566 else:567 self.handler = handlermodified:requests/monkeys.py+60 added-2 removed
7 unmodified lines8 9 """10 11 import urllib212+import re13 13-14 class Request(urllib2.Request):15 """Hidden wrapper around the urllib2.Request object. Allows for manual16 setting of HTTP methods.17 """7 unmodified lines25 return self.method26 27 return urllib2.Request.get_method(self)28 29-class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):29 30+class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31+ """HTTP Redirect handler."""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):40+ """HTTP Basic Auth Handler with authentication loop fixes."""41 42 def __init__(self, *args, **kwargs):43 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44 self.retried_req = None45+ self.retried = 046 47+48 def reset_retry_count(self):49 # Python 2.6.5 will call this on 401 or 407 errors and thus loop50 # forever. We disable reset_retry_count completely and reset in51 # http_error_auth_reqed instead.52 pass53 54+55 def http_error_auth_reqed(self, auth_header, host, req, headers):56 # Reset the retry counter once for each request.57 if req is not self.retried_req:58 self.retried_req = req4 unmodified lines63 )64 65 66 67+class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):68+ """HTTP Basic Auth Handler with forced Authentication."""69+70+ auth_header = 'Authorization'71+ rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'72+ 'realm=(["\'])(.*?)\\2', re.I)73+74+ def __init__(self, *args, **kwargs):75+ HTTPBasicAuthHandler.__init__(self, *args, **kwargs)76+77+78+ def http_error_401(self, req, fp, code, msg, headers):79+ url = req.get_full_url()80+ response = self._http_error_auth_reqed('www-authenticate', url, req, headers)81+ self.reset_retry_count()82+ return response83+84+ http_error_404 = http_error_40185+86+87+ def _http_error_auth_reqed(self, authreq, host, req, headers):88+89+ authreq = headers.get(authreq, None)90+91+ if self.retried > 5:92+ # retry sending the username:password 5 times before failing.93+ raise urllib2.HTTPError(req.get_full_url(), 401, "basic auth failed",94+ headers, None)95+ else:96+ self.retried += 197+98+ if authreq:99+100+ mo = self.rx.search(authreq)101+102+ if mo:103+ scheme, quote, realm = mo.groups()104+105+ if scheme.lower() == 'basic':106+ response = self.retry_http_basic_auth(host, req, realm)107+108+ if response and response.code not in (401, 404):109+ self.retried = 0110+ return response111+ else:112+ response = self.retry_http_basic_auth(host, req, 'Realm')113+114+ if response and response.code not in (401, 404):115+ self.retried = 0116+ return response117+118+119+120 class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):121 122 def __init__(self, *args, **kwargs):123 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)25 unmodified linesmodified:requests/structures.py+25 added-6 removed
7 unmodified lines8 9 """10 11 class CaseInsensitiveDict(dict):12- """Case-insensitive Dictionary for :class:`Response <models.Response>` Headers.12+ """Case-insensitive Dictionary13 14 For example, ``headers['content-encoding']`` will return the15 value of a ``'Content-Encoding'`` response header."""16 17- def _lower_keys(self):18- return map(str.lower, self.keys())17+ @property18+ def lower_keys(self):19+ if not hasattr(self, '_lower_keys') or not self._lower_keys:20+ self._lower_keys = dict((k.lower(), k) for k in self.iterkeys())21+ return self._lower_keys22 23+ def _clear_lower_keys(self):24+ if hasattr(self, '_lower_keys'):25+ self._lower_keys.clear()26 21- def __contains__(self, key):22- return key.lower() in self._lower_keys()27+ def __setitem__(self, key, value):28+ dict.__setitem__(self, key, value)29+ self._clear_lower_keys()30 31+ def __delitem__(self, key):32+ dict.__delitem__(self, key)33+ self._lower_keys.clear()34 35+ def __contains__(self, key):36+ return key.lower() in self.lower_keys37+38 def __getitem__(self, key):39 # We allow fall-through here, so values default to None40 if key in self:28- return self.items()[self._lower_keys().index(key.lower())][1]41+ return dict.__getitem__(self, self.lower_keys[key.lower()])42+43+ def get(self, key, default=None):44+ if key in self:45+ return self[key]46+ else:47+ return defaultmodified:.gitignore+2 added-1 removed
3 unmodified lines4 nosetests.xml5 pylint.txt6 *.pyc7 docs/_build8-toy.py8+toy.py9+.gitignoremodified:AUTHORS+3 added
26 unmodified lines27 - Miguel Olivares <miguel@moliware.com>28 - Alberto Paro29 - Jérémy Bethmont30 - 潘旭 (Xu Pan)31+- Tamás Gulácsi32+- Rubén Abad33+- Peter Mansermodified:HISTORY.rst+9 added-2 removed
1 History2 -------3 4-0.5.1 (?)5-+++++++++4+0.5.1 (2011-07-23)5+++++++++++++++++++6 7 * International Domain Name Support!8+* Access headers without fetching entire body (``read()``)9+* Use lists as dicts for parameters10+* Add Forced Basic Authentication11+* Forced Basic is default authentication type12+* ``python-requests.org`` default User-Agent header13+* CaseInsensitiveDict lower-case caching14+* Response.history bugfix15 16 17 0.5.0 (2011-06-21)18 ++++++++++++++++++116 unmodified linesmodified:README.rst+1 added-1 removed
41 unmodified lines42 43 44 Uh oh, we're not authorized! Let's add authentication. ::45 46- >>> r = requests.get(https://httpbin.ep.io/basic-auth/user/pass', auth=('user', 'pass'))46+ >>> r = requests.get('https://httpbin.ep.io/basic-auth/user/pass', auth=('user', 'pass'))47 48 >>> r.status_code49 20050 110 unmodified linesmodified:test_requests.py+38 added-2 removed
4 unmodified lines5 6 import unittest7 import cookielib8 9+try:9-import omnijson as json10+ import omnijson as json11+except ImportError:12+ import json13 14 import requests15 16 308 unmodified lines325 self.assertEquals(rbody.get('data'), 'foobar')326 327 def test_idna(self):328 r = requests.get(u'http://➡.ws/httpbin')326- self.assertEqual(r.url, HTTPBIN_URL)329+ assert 'httpbin' in r.url330 331+ def test_urlencoded_get_query_multivalued_param(self):332+ r = requests.get(httpbin('get'), params=dict(test=['foo','baz']))333+ self.assertEquals(r.status_code, 200)334+ self.assertEquals(r.url, httpbin('get?test=foo&test=baz'))335 336+ def test_urlencoded_post_querystring_multivalued(self):337+ r = requests.post(httpbin('post'), params=dict(test=['foo','baz']))338+ self.assertEquals(r.status_code, 200)339+ self.assertEquals(r.headers['content-type'], 'application/json')340+ self.assertEquals(r.url, httpbin('post?test=foo&test=baz'))341+ rbody = json.loads(r.content)342+ self.assertEquals(rbody.get('form'), {}) # No form supplied343+ self.assertEquals(rbody.get('data'), '')344+345+ def test_urlencoded_post_query_multivalued_and_data(self):346+ r = requests.post(httpbin('post'), params=dict(test=['foo','baz']),347+ data=dict(test2="foobar",test3=['foo','baz']))348+ self.assertEquals(r.status_code, 200)349+ self.assertEquals(r.headers['content-type'], 'application/json')350+ self.assertEquals(r.url, httpbin('post?test=foo&test=baz'))351+ rbody = json.loads(r.content)352+ self.assertEquals(rbody.get('form'), dict(test2='foobar',test3='foo'))353+ self.assertEquals(rbody.get('data'), '')354+355+356+ def test_redirect_history(self):357+ r = requests.get(httpbin('redirect', '3'))358+ self.assertEquals(r.status_code, 200)359+ self.assertEquals(len(r.history), 3)360+361+ r = requests.get(httpsbin('redirect', '3'))362+ self.assertEquals(r.status_code, 200)363+ self.assertEquals(len(r.history), 3)364+365 if __name__ == '__main__':366 unittest.main()