Merge branch 'develop'
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 5b5b3de, 02cf3dc · Browse files · 12 files·+396 added−347 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+396 added−347 removed
- other:+396 added−347 removed
Provenance
- Commit
6b9cb05- Tree
d862093- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
5b5b3de- Parent 2
02cf3dc
12 files changed+396 added−347 removed
modified:docs/user/advanced.rst+33 added
155 unmodified lines156 }157 }158 159 160+Custom Authentication161+---------------------162 163+Requests allows you to use specify your own authentication mechanism.164+165+When you pass our authentication tuple to a request method, the first166+string is the type of authentication. 'basic' is inferred if none is167+provided.168+169+You can pass in a callable object instead of a string for the first item170+in the tuple, and it will be used in place of the built in authentication171+callbacks.172+173+Let's pretend that we have a web service that will only respond if the174+``X-Pizza`` header is set to a password value. Unlikely, but just go with it.175+176+We simply need to define a callback function that will be used to update the177+Request object, right before it is dispatched.178+179+::180+181+ def pizza_auth(r, username):182+ """Attaches HTTP Pizza Authentication to the given Request object.183+ """184+ r.headers['X-Pizza'] = username185+186+ return r187+188+Then, we can make a request using our Pizza Auth::189+190+ >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))191+ <Response [200]>192+193+194 Verbose Logging195 ---------------196 197 If you want to get a good look at what HTTP requests are being sent8 unmodified linesmodified:docs/user/quickstart.rst+29 added
134 unmodified lines135 136 >>> r = requests.get(url, cookies=cookies)137 >>> r.content138 '{"cookies": {"cookies_are": "working"}}'139+140+141+Basic Authentication142+--------------------143+144+Most web services require authentication. There many different types of145+authentication, but the most common is called HTTP Basic Auth.146+147+Making requests with Basic Auth is easy, with Requests::148+149+ >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))150+ <Response [200]>151+152+153+Digest Authentication154+---------------------155+156+Another popular form of protecting web service is Digest Authentication.157+158+Requests supports it!::159+160+ >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'161+ >>> requests.get(url, auth=('digest', 'user', 'pass'))162+ <Response [200]>163+164+165+-----------------------166+167+Ready for more? Check out the advanced_ section.modified:requests/__init__.py+2 added-2 removed
13 unmodified lines14 15 """16 17 __title__ = 'requests'18-__version__ = '0.7.0'19-__build__ = 0x00070018+__version__ = '0.7.1'19+__build__ = 0x00070120 __author__ = 'Kenneth Reitz'21 __license__ = 'ISC'22 __copyright__ = 'Copyright 2011 Kenneth Reitz'23 10 unmodified linesmodified:requests/async.py+10 added-16 removed
26 unmodified lines27 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'28 )29 30 31-def _patched(f):31+def patched(f):32 """Patches a given API function to not send."""33 34 def wrapped(*args, **kwargs):35 return f(*args, return_response=False, **kwargs)36 37 return wrapped38 39 40-def _send(r, pools=None):40+def send(r, pools=None):41 """Sends a given Request object."""42 43 if pools:44 r._pools = pools45 46 r.send()47 48- # Post-request hook.49- r = dispatch_hook('post_request', r.hooks, r)50-51- # Response manipulation hook.52- r.response = dispatch_hook('response', r.hooks, r.response)53-48 return r.response49 50 51 # Patched requests.api functions.58-get = _patched(api.get)59-head = _patched(api.head)60-post = _patched(api.post)61-put = _patched(api.put)62-patch = _patched(api.patch)63-delete = _patched(api.delete)64-request = _patched(api.request)52+get = patched(api.get)53+head = patched(api.head)54+post = patched(api.post)55+put = patched(api.put)56+patch = patched(api.patch)57+delete = patched(api.delete)58+request = patched(api.request)59 60 61 def map(requests, prefetch=True):62 """Concurrently converts a list of Requests to Responses.1 unmodified line64 :param requests: a collection of Request objects.65 :param prefetch: If False, the content will not be downloaded immediately.66 """67 74- jobs = [gevent.spawn(_send, r) for r in requests]68+ jobs = [gevent.spawn(send, r) for r in requests]69 gevent.joinall(jobs)70 71 if prefetch:72 [r.response.content for r in requests]6 unmodified linesadded:requests/auth.py+151 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.auth5+~~~~~~~~~~~~~6+7+This module contains the authentication handlers for Requests.8+"""9+10+import time11+import hashlib12+13+from base64 import b64encode14+from urlparse import urlparse15+16+from .utils import randombytes, parse_dict_header17+18+19+def http_basic(r, username, password):20+ """Attaches HTTP Basic Authentication to the given Request object.21+ Arguments should be considered non-positional.22+23+ """24+ username = str(username)25+ password = str(password)26+27+ auth_s = b64encode('%s:%s' % (username, password))28+ r.headers['Authorization'] = ('Basic %s' % auth_s)29+30+ return r31+32+33+def http_digest(r, username, password):34+ """Attaches HTTP Digest Authentication to the given Request object.35+ Arguments should be considered non-positional.36+ """37+38+ def handle_401(r):39+ """Takes the given response and tries digest-auth, if needed."""40+41+ s_auth = r.headers.get('www-authenticate', '')42+43+ if 'digest' in s_auth.lower():44+45+ last_nonce = ''46+ nonce_count = 047+48+ chal = parse_dict_header(s_auth.replace('Digest ', ''))49+50+ realm = chal['realm']51+ nonce = chal['nonce']52+ qop = chal.get('qop')53+ algorithm = chal.get('algorithm', 'MD5')54+ opaque = chal.get('opaque', None)55+56+ algorithm = algorithm.upper()57+ # lambdas assume digest modules are imported at the top level58+ if algorithm == 'MD5':59+ H = lambda x: hashlib.md5(x).hexdigest()60+ elif algorithm == 'SHA':61+ H = lambda x: hashlib.sha1(x).hexdigest()62+ # XXX MD5-sess63+ KD = lambda s, d: H("%s:%s" % (s, d))64+65+ if H is None:66+ return None67+68+ # XXX not implemented yet69+ entdig = None70+ path = urlparse(r.request.url).path71+72+ A1 = "%s:%s:%s" % (username, realm, password)73+ A2 = "%s:%s" % (r.request.method, path)74+75+ if qop == 'auth':76+ if nonce == last_nonce:77+ nonce_count += 178+ else:79+ nonce_count = 180+ last_nonce = nonce81+82+ ncvalue = '%08x' % nonce_count83+ cnonce = (hashlib.sha1("%s:%s:%s:%s" % (84+ nonce_count, nonce, time.ctime(), randombytes(8)))85+ .hexdigest()[:16]86+ )87+ noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))88+ respdig = KD(H(A1), noncebit)89+ elif qop is None:90+ respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))91+ else:92+ # XXX handle auth-int.93+ return None94+95+ # XXX should the partial digests be encoded too?96+ base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \97+ 'response="%s"' % (username, realm, nonce, path, respdig)98+ if opaque:99+ base += ', opaque="%s"' % opaque100+ if entdig:101+ base += ', digest="%s"' % entdig102+ base += ', algorithm="%s"' % algorithm103+ if qop:104+ base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)105+106+107+ r.request.headers['Authorization'] = 'Digest %s' % (base)108+ r.request.send(anyway=True)109+ _r = r.request.response110+ _r.history.append(r)111+ print _r.status_code112+113+ # r.request.response114+115+ print locals()116+117+ print _r.headers118+ return _r119+120+ return r121+122+ r.hooks['response'] = handle_401123+ return r124+125+126+def dispatch(t):127+ """Given an auth tuple, return an expanded version."""128+129+ if not t:130+ return t131+ else:132+ t = list(t)133+134+ # Make sure they're passing in something.135+ assert len(t) >= 2136+137+ # If only two items are passed in, assume HTTPBasic.138+ if (len(t) == 2):139+ t.insert(0, 'basic')140+141+ # Allow built-in string referenced auths.142+ if isinstance(t[0], basestring):143+ if t[0] in ('basic', 'forced_basic'):144+ t[0] = http_basic145+ elif t[0] in ('digest',):146+ t[0] = http_digest147+148+ # Return a custom callable.149+ return (t[0], tuple(t[1:]))150+151+modified:requests/defaults.py+1 added-1 removed
23 unmodified lines24 25 26 defaults['base_headers'] = {27 'User-Agent': 'python-requests/%s' % __version__,28- 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),28+ 'Accept-Encoding': ', '.join(('identity', 'deflate', 'compress', 'gzip')),29 }30 31 defaults['proxies'] = {}32 defaults['verbose'] = None6 unmodified linesmodified:requests/models.py+23 added-202 removed
14 unmodified lines15 from urllib2 import HTTPError16 from urlparse import urlparse, urlunparse, urljoin17 from datetime import datetime18 19+from .hooks import dispatch_hook20 from .structures import CaseInsensitiveDict21 from .packages.poster.encode import multipart_encode22 from .packages.poster.streaminghttp import register_openers, get_handlers23 from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)24 from .status_codes import codes25 from .exceptions import Timeout, URLRequired, TooManyRedirects26 from .monkeys import Request as _Request26-from .monkeys import (27- HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler,28- HTTPDigestAuthHandler, HTTPRedirectHandler)27+from .monkeys import HTTPRedirectHandler28 29+from .auth import dispatch as auth_dispatch30 31 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)32 33 59 unmodified lines93 #: :class:`Response <Response>` instance, containing94 #: content and metadata of HTTP Response, once :attr:`sent <send>`.95 self.response = Response()96 97- if isinstance(auth, (list, tuple)):98- auth = AuthObject(*auth)99- if not auth:100- auth = auth_manager.get_auth(self.url)97+ #: Authentication tuple to attach to :class:`Request <Request>`.98+ self.auth = auth_dispatch(auth)99 102- #: :class:`AuthObject` to attach to :class:`Request <Request>`.103- self.auth = auth104-100 #: CookieJar to attach to :class:`Request <Request>`.101 self.cookies = cookies102 103 #: Dictionary of configurations for this request.15 unmodified lines119 headers[k] = v120 121 self.headers = headers122 123+ # Pre-request hook.124+ r = dispatch_hook('pre_request', hooks, self)125+ self.__dict__.update(r.__dict__)126 127+128 def __repr__(self):129 return '<Request [%s]>' % (self.method)130 131 4 unmodified lines136 137 if self.cookies is not None:138 _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))139 141- if self.auth:142- if not isinstance(self.auth.handler,143- (urllib2.AbstractBasicAuthHandler,144- urllib2.AbstractDigestAuthHandler)):145-146- # TODO: REMOVE THIS COMPLETELY147- auth_manager.add_password(148- self.auth.realm, self.url,149- self.auth.username,150- self.auth.password)151-152- self.auth.handler = self.auth.handler(auth_manager)153- auth_manager.add_auth(self.url, self.auth)154-155- _handlers.append(self.auth.handler)156-140 if self.proxies:141 _handlers.append(urllib2.ProxyHandler(self.proxies))142 143 _handlers.append(HTTPRedirectHandler)186 unmodified lines330 else:331 data = self._enc_data332 headers = {}333 334+ if self.auth:335+ auth_func, auth_args = self.auth336+337+ r = auth_func(self, *auth_args)338+339+ self.__dict__.update(r.__dict__)340+341 # Build the Urllib2 Request.342 req = _Request(url, data=data, headers=headers, method=self.method)343 344 # Add the headers to the request.43 unmodified lines388 389 390 self.sent = self.response.ok391 392+ # Response manipulation hook.393+ self.response = dispatch_hook('response', self.hooks, self.response)394+395+ # Post-request hook.396+ r = dispatch_hook('post_request', self.hooks, self)397+ self.__dict__.update(r.__dict__)398+399 return self.sent400 401 402 class Response(object):113 unmodified lines516 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""517 if self.error:518 raise self.error519 523-524-525-class AuthManager(object):526- """Requests Authentication Manager."""527-528- def __new__(cls):529- singleton = cls.__dict__.get('__singleton__')530- if singleton is not None:531- return singleton532-533- cls.__singleton__ = singleton = object.__new__(cls)534-535- return singleton536-537-538- def __init__(self):539- self.passwd = {}540- self._auth = {}541-542-543- def __repr__(self):544- return '<AuthManager [%s]>' % (self.method)545-546-547- def add_auth(self, uri, auth):548- """Registers AuthObject to AuthManager."""549-550- uri = self.reduce_uri(uri, False)551-552- # try to make it an AuthObject553- if not isinstance(auth, AuthObject):554- try:555- auth = AuthObject(*auth)556- except TypeError:557- pass558-559- self._auth[uri] = auth560-561-562- def add_password(self, realm, uri, user, passwd):563- """Adds password to AuthManager."""564- # uri could be a single URI or a sequence565- if isinstance(uri, basestring):566- uri = [uri]567-568- reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])569-570- if reduced_uri not in self.passwd:571- self.passwd[reduced_uri] = {}572- self.passwd[reduced_uri] = (user, passwd)573-574-575- def find_user_password(self, realm, authuri):576- for uris, authinfo in self.passwd.iteritems():577- reduced_authuri = self.reduce_uri(authuri, False)578- for uri in uris:579- if self.is_suburi(uri, reduced_authuri):580- return authinfo581-582- return (None, None)583-584-585- def get_auth(self, uri):586- (in_domain, in_path) = self.reduce_uri(uri, False)587-588- for domain, path, authority in (589- (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()590- ):591- if in_domain == domain:592- if path in in_path:593- return authority594-595-596- def reduce_uri(self, uri, default_port=True):597- """Accept authority or URI and extract only the authority and path."""598-599- # note HTTP URLs do not have a userinfo component600- parts = urllib2.urlparse.urlsplit(uri)601-602- if parts[1]:603- # URI604- scheme = parts[0]605- authority = parts[1]606- path = parts[2] or '/'607- else:608- # host or host:port609- scheme = None610- authority = uri611- path = '/'612-613- host, port = urllib2.splitport(authority)614-615- if default_port and port is None and scheme is not None:616- dport = {"http": 80,617- "https": 443,618- }.get(scheme)619- if dport is not None:620- authority = "%s:%d" % (host, dport)621-622- return authority, path623-624-625- def is_suburi(self, base, test):626- """Check if test is below base in a URI tree627-628- Both args must be URIs in reduced form.629- """630- if base == test:631- return True632- if base[0] != test[0]:633- return False634- common = urllib2.posixpath.commonprefix((base[1], test[1]))635- if len(common) == len(base[1]):636- return True637- return False638-639-640- def empty(self):641- self.passwd = {}642-643-644- def remove(self, uri, realm=None):645- # uri could be a single URI or a sequence646- if isinstance(uri, basestring):647- uri = [uri]648-649- for default_port in True, False:650- reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])651- del self.passwd[reduced_uri][realm]652-653-654- def __contains__(self, uri):655- # uri could be a single URI or a sequence656- if isinstance(uri, basestring):657- uri = [uri]658-659- uri = tuple([self.reduce_uri(u, False) for u in uri])660-661- if uri in self.passwd:662- return True663-664- return False665-666-auth_manager = AuthManager()667-668-669-670-class AuthObject(object):671- """The :class:`AuthObject` is a simple HTTP Authentication token. When672- given to a Requests function, it enables Basic HTTP Authentication for that673- Request. You can also enable Authorization for domain realms with AutoAuth.674- See AutoAuth for more details.675-676- :param username: Username to authenticate with.677- :param password: Password for given username.678- :param realm: (optional) the realm this auth applies to679- :param handler: (optional) basic || digest || proxy_basic || proxy_digest680- """681-682- _handlers = {683- 'basic': HTTPBasicAuthHandler,684- 'forced_basic': HTTPForcedBasicAuthHandler,685- 'digest': HTTPDigestAuthHandler,686- 'proxy_basic': urllib2.ProxyBasicAuthHandler,687- 'proxy_digest': urllib2.ProxyDigestAuthHandler688- }689-690- def __init__(self, username, password, handler='forced_basic', realm=None):691- self.username = username692- self.password = password693- self.realm = realm694-695- if isinstance(handler, basestring):696- self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)697- else:698- self.handler = handlermodified:requests/monkeys.py+5 added-114 removed
27 unmodified lines28 29 30 class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31 """HTTP Redirect handler."""32- def http_error_301(self, req, fp, code, msg, headers):32+ def _pass(self, req, fp, code, msg, headers):33 pass34 35- http_error_302 = http_error_303 = http_error_307 = http_error_30135+ http_error_302 = _pass36+ http_error_303 = _pass37+ http_error_307 = _pass38+ http_error_301 = _pass39 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 = req59- self.retried = 060-61- return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(62- self, auth_header, host, req, headers63- )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)124- self.retried_req = None125-126- def reset_retry_count(self):127- # Python 2.6.5 will call this on 401 or 407 errors and thus loop128- # forever. We disable reset_retry_count completely and reset in129- # http_error_auth_reqed instead.130- pass131-132- def http_error_auth_reqed(self, auth_header, host, req, headers):133- # Reset the retry counter once for each request.134- if req is not self.retried_req:135- self.retried_req = req136- self.retried = 0137- # In python < 2.5 AbstractDigestAuthHandler raises a ValueError if138- # it doesn't know about the auth type requested. This can happen if139- # somebody is using BasicAuth and types a bad password.140-141- try:142- return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(143- self, auth_header, host, req, headers)144- except ValueError, inst:145- arg = inst.args[0]146- if arg.startswith("AbstractDigestAuthHandler doesn't know "):147- return148- raisemodified:requests/sessions.py+1 added-9 removed
110 unmodified lines111 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.112 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.113 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.114 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.115- :param auth: (optional) AuthObject to enable Basic HTTP Auth.115+ :param auth: (optional) Auth typle to enable Basic/Digest/Custom HTTP Auth.116 :param timeout: (optional) Float describing the timeout of the request.117 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.118 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.119 :param return_response: (optional) If False, an un-sent Request object will returned.41 unmodified lines161 args = dispatch_hook('args', hooks, args)162 163 r = Request(**args)164 165- # Pre-request hook.166- r = dispatch_hook('pre_request', hooks, r)167-165 # Don't send if asked nicely.166 if not return_response:167 return r168 169 # Send the HTTP Request.170 r.send()171 175- # Post-request hook.176- r = dispatch_hook('post_request', hooks, r)172 178- # Response manipulation hook.179- r.response = dispatch_hook('response', hooks, r.response)180-173 return r.response174 175 176 def get(self, url, **kwargs):69 unmodified linesmodified:requests/utils.py+109 added
10 unmodified lines11 12 import cgi13 import codecs14 import cookielib15+import os16+import random17 import re18 import zlib19 20+from urllib2 import parse_http_list as _parse_list_header21 22+23+# From mitsuhiko/werkzeug (used with permission).24+def parse_list_header(value):25+ """Parse lists as described by RFC 2068 Section 2.26+27+ In particular, parse comma-separated lists where the elements of28+ the list may include quoted-strings. A quoted-string could29+ contain a comma. A non-quoted string could have quotes in the30+ middle. Quotes are removed automatically after parsing.31+32+ It basically works like :func:`parse_set_header` just that items33+ may appear multiple times and case sensitivity is preserved.34+35+ The return value is a standard :class:`list`:36+37+ >>> parse_list_header('token, "quoted value"')38+ ['token', 'quoted value']39+40+ To create a header from the :class:`list` again, use the41+ :func:`dump_header` function.42+43+ :param value: a string with a list header.44+ :return: :class:`list`45+ """46+ result = []47+ for item in _parse_list_header(value):48+ if item[:1] == item[-1:] == '"':49+ item = unquote_header_value(item[1:-1])50+ result.append(item)51+ return result52+53+54+# From mitsuhiko/werkzeug (used with permission).55+def parse_dict_header(value):56+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and57+ convert them into a python dict:58+59+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')60+ >>> type(d) is dict61+ True62+ >>> sorted(d.items())63+ [('bar', 'as well'), ('foo', 'is a fish')]64+65+ If there is no value for a key it will be `None`:66+67+ >>> parse_dict_header('key_without_value')68+ {'key_without_value': None}69+70+ To create a header from the :class:`dict` again, use the71+ :func:`dump_header` function.72+73+ :param value: a string with a dict header.74+ :return: :class:`dict`75+ """76+ result = {}77+ for item in _parse_list_header(value):78+ if '=' not in item:79+ result[item] = None80+ continue81+ name, value = item.split('=', 1)82+ if value[:1] == value[-1:] == '"':83+ value = unquote_header_value(value[1:-1])84+ result[name] = value85+ return result86+87+88+# From mitsuhiko/werkzeug (used with permission).89+def unquote_header_value(value, is_filename=False):90+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).91+ This does not use the real unquoting but what browsers are actually92+ using for quoting.93+94+ :param value: the header value to unquote.95+ """96+ if value and value[0] == value[-1] == '"':97+ # this is not the real unquoting, but fixing this so that the98+ # RFC is met will result in bugs with internet explorer and99+ # probably some other browsers as well. IE for example is100+ # uploading files with "C:\foo\bar.txt" as filename101+ value = value[1:-1]102+103+ # if this is a filename and the starting characters look like104+ # a UNC path, then just return the value without quotes. Using the105+ # replace sequence below on a UNC path has the effect of turning106+ # the leading double slash into a single slash and then107+ # _fix_ie_filename() doesn't work correctly. See #458.108+ if not is_filename or value[:2] != '\\\\':109+ return value.replace('\\\\', '\\').replace('\\"', '"')110+ return value111+112+113 def header_expand(headers):114 """Returns an HTTP Header value string from a dictionary.115 116 Example expansion::39 unmodified lines156 return ''.join(collector)157 158 159 160+def randombytes(n):161+ """Return n random bytes."""162+ # Use /dev/urandom if it is available. Fall back to random module163+ # if not. It might be worthwhile to extend this function to use164+ # other platform-specific mechanisms for getting random bytes.165+ if os.path.exists("/dev/urandom"):166+ f = open("/dev/urandom")167+ s = f.read(n)168+ f.close()169+ return s170+ else:171+ L = [chr(random.randrange(0, 256)) for i in range(n)]172+ return "".join(L)173+174+175 def dict_from_cookiejar(cj):176 """Returns a key/value dictionary from a CookieJar.177 178 :param cj: CookieJar object to extract cookies from.185 unmodified linesmodified:HISTORY.rst+8 added
1 History2 -------3 4+0.7.1 (2011-10-23)5+++++++++++++++++++6+7+* Move away from urllib2 authentication handling.8+* Fully Remove AuthManager, AuthObject, &c.9+* New tuple-based auth system with handler callbacks.10+11+12 0.7.0 (2011-10-22)13 ++++++++++++++++++14 15 * Sessions are now the primary interface.198 unmodified linesmodified:test_requests.py+24 added-3 removed
137 unmodified lines138 r = requests.patch(httpbin('patch'))139 self.assertEqual(r.status_code, 200)140 141 142- def test_AUTH_HTTP_200_OK_GET(self):142+ def test_BASICAUTH_HTTP_200_OK_GET(self):143 144 for service in SERVICES:145 146 auth = ('user', 'pass')147 url = service('basic-auth', 'user', 'pass')148 149 r = requests.get(url, auth=auth)150- # print r.__dict__150 self.assertEqual(r.status_code, 200)151 153-152 r = requests.get(url)153+ self.assertEqual(r.status_code, 401)154+155+156+ s = requests.session(auth=auth)157+ r = s.get(url)158 self.assertEqual(r.status_code, 200)159 160 161+ def test_DIGESTAUTH_HTTP_200_OK_GET(self):162+163+ for service in SERVICES:164+165+ auth = ('digest', 'user', 'pass')166+ url = service('digest-auth', 'auth', 'user', 'pass')167+168+ r = requests.get(url, auth=auth)169+ self.assertEqual(r.status_code, 200)170+171+ r = requests.get(url)172+ self.assertEqual(r.status_code, 401)173+174+175+ s = requests.session(auth=auth)176+ r = s.get(url)177+ self.assertEqual(r.status_code, 200)178+179 def test_POSTBIN_GET_POST_FILES(self):180 181 for service in SERVICES:182 351 unmodified lines