Skip to content
Myr

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

16 files+235 added−30 removed

added:debian/changelog+5 added
1python-requests (0.4.1-0) testing; urgency=low23 * Initial Debian package45 -- Bruno Clermont <bruno.clermont@gmail.com> Thu, 26 May 2011 16:25:00 -0500
added:debian/compat+1 added
15
added:debian/control+13 added
1Source: python-requests2Section: python3Priority: optional4Maintainer: Bruno Clermont <bruno.clermont@gmail.com>5Homepage: https://github.com/bclermont/requests6Bugs: https://github.com/bclermont/requests/issues7Build-Depends: debhelper, python-support89Package: python-requests10Architecture: all11Depends: ${python:Depends}, python-support12Provides: ${python:Provides}13Description: Python HTTP Requests for Humans.
added:debian/docs+1 added
1docs/user/*.rst
added:debian/pyversions+1 added
12.4-
added:debian/rules+42 added
1#!/usr/bin/make -f23# Verbose mode4#export DH_VERBOSE=156clean:7 dh_testdir8 dh_testroot910 rm -rf build requests.egg-info11# find django-sentry/ -name *.pyc | xargs rm -f1213 dh_clean1415build:16 dh_testdir1718 python setup.py build1920install:21 dh_testdir22 dh_installdirs2324 python setup.py install --root $(CURDIR)/debian/python-requests2526binary-indep: install2728binary-arch: install29 dh_install30 dh_installdocs31# dh_installchangelogs32 dh_compress33 dh_fixperms34 dh_pysupport35 dh_gencontrol36 dh_installdeb37 dh_md5sums38 dh_builddeb -- -Z lzma -z93940binary: binary-indep binary-arch41.PHONY: build clean binary-indep binary-arch binary42
modified:requests/config.py+3 added-1 removed
51 unmodified lines
52 except AttributeError:53 return None54 return object.__getattribute__(self, key)5556settings = Settings()56settings = Settings()57settings.base_headers = {'User-Agent': 'python-requests.org'}58settings.accept_gzip = True
modified:requests/core.py+2 added-2 removed
10 unmodified lines
1112"""1314__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 lines
modified:requests/models.py+29 added-13 removed
14 unmodified lines
15from urlparse import urlparse, urlunparse16from datetime import datetime1718from .config import settings19from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers23from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod
56 unmodified lines
80 #: True if Request has been sent.81 self.sent = False828384 # Header manipulation and defaults.8586 if settings.accept_gzip:87 settings.base_headers.update({'Accept-Encoding': 'gzip'})8889 if headers:90 headers = CaseInsensitiveDict(self.headers)91 else:92 headers = CaseInsensitiveDict()9394 for (k, v) in settings.base_headers.items():95 if k not in headers:96 headers[k] = v9798 self.headers = headers99100101 def __repr__(self):102 return '<Request [%s]>' % (self.method)103104
76 unmodified lines
181 history = []182183 r = build(resp)184168 if r.status_code in REDIRECT_STATI:169 self.redirect = True185 if r.status_code in REDIRECT_STATI and not self.redirect:186171 if self.redirect:172187 while (188 ('location' in r.headers) and189 ((self.method in ('GET', 'HEAD')) or190 (r.status_code is 303) or
33 unmodified lines
224 def _encode_params(data):225 """Encode parameters in a piece of data.226227 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.230231 Otherwise, assumes the data is already encoded appropriately, and232 returns it twice.233234 """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 lines
549 """550551 _handlers = {552 'basic': HTTPBasicAuthHandler,553 'forced_basic': HTTPForcedBasicAuthHandler,554 'digest': HTTPDigestAuthHandler,555 'proxy_basic': urllib2.ProxyBasicAuthHandler,556 'proxy_digest': urllib2.ProxyDigestAuthHandler557 }558543 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 = realm563564 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 = handler
modified:requests/monkeys.py+60 added-2 removed
7 unmodified lines
89"""1011import urllib212import re131314class Request(urllib2.Request):15 """Hidden wrapper around the urllib2.Request object. Allows for manual16 setting of HTTP methods.17 """
7 unmodified lines
25 return self.method2627 return urllib2.Request.get_method(self)2829class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):2930class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31 """HTTP Redirect handler."""32 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):40 """HTTP Basic Auth Handler with authentication loop fixes."""4142 def __init__(self, *args, **kwargs):43 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44 self.retried_req = None45 self.retried = 0464748 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 pass535455 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 = req
4 unmodified lines
63 )64656667class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):68 """HTTP Basic Auth Handler with forced Authentication."""6970 auth_header = 'Authorization'71 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'72 'realm=(["\'])(.*?)\\2', re.I)7374 def __init__(self, *args, **kwargs):75 HTTPBasicAuthHandler.__init__(self, *args, **kwargs)767778 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 response8384 http_error_404 = http_error_401858687 def _http_error_auth_reqed(self, authreq, host, req, headers):8889 authreq = headers.get(authreq, None)9091 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 += 19798 if authreq:99100 mo = self.rx.search(authreq)101102 if mo:103 scheme, quote, realm = mo.groups()104105 if scheme.lower() == 'basic':106 response = self.retry_http_basic_auth(host, req, realm)107108 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')113114 if response and response.code not in (401, 404):115 self.retried = 0116 return response117118119120class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):121122 def __init__(self, *args, **kwargs):123 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)
25 unmodified lines
modified:requests/structures.py+25 added-6 removed
7 unmodified lines
89"""1011class CaseInsensitiveDict(dict):12 """Case-insensitive Dictionary for :class:`Response <models.Response>` Headers.12 """Case-insensitive Dictionary1314 For example, ``headers['content-encoding']`` will return the15 value of a ``'Content-Encoding'`` response header."""1617 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_keys2223 def _clear_lower_keys(self):24 if hasattr(self, '_lower_keys'):25 self._lower_keys.clear()2621 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()3031 def __delitem__(self, key):32 dict.__delitem__(self, key)33 self._lower_keys.clear()3435 def __contains__(self, key):36 return key.lower() in self.lower_keys3738 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()])4243 def get(self, key, default=None):44 if key in self:45 return self[key]46 else:47 return default
modified:.gitignore+2 added-1 removed
3 unmodified lines
4nosetests.xml5pylint.txt6*.pyc7docs/_build8toy.py8toy.py9.gitignore
modified:AUTHORS+3 added
26 unmodified lines
27- Miguel Olivares <miguel@moliware.com>28- Alberto Paro29- Jérémy Bethmont30- 潘旭 (Xu Pan)31- Tamás Gulácsi32- Rubén Abad33- Peter Manser
modified:HISTORY.rst+9 added-2 removed
1History2-------340.5.1 (?)5+++++++++40.5.1 (2011-07-23)5++++++++++++++++++67* 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 bugfix1516170.5.0 (2011-06-21)18++++++++++++++++++
116 unmodified lines
modified:README.rst+1 added-1 removed
41 unmodified lines
424344Uh oh, we're not authorized! Let's add authentication. ::4546 >>> 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'))4748 >>> r.status_code49 20050
110 unmodified lines
modified:test_requests.py+38 added-2 removed
4 unmodified lines
56import unittest7import cookielib89try:9import omnijson as json10 import omnijson as json11except ImportError:12 import json1314import requests1516
308 unmodified lines
325 self.assertEquals(rbody.get('data'), 'foobar')326327 def test_idna(self):328 r = requests.get(u'http://➡.ws/httpbin')326 self.assertEqual(r.url, HTTPBIN_URL)329 assert 'httpbin' in r.url330331 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'))335336 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'), '')344345 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'), '')354355356 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)360361 r = requests.get(httpsbin('redirect', '3'))362 self.assertEquals(r.status_code, 200)363 self.assertEquals(len(r.history), 3)364365if __name__ == '__main__':366 unittest.main()