Skip to content
Myr

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

12 files+396 added−347 removed

modified:docs/user/advanced.rst+33 added
155 unmodified lines
156 }157 }158159160Custom Authentication161---------------------162163Requests allows you to use specify your own authentication mechanism.164165When you pass our authentication tuple to a request method, the first166string is the type of authentication. 'basic' is inferred if none is167provided.168169You can pass in a callable object instead of a string for the first item170in the tuple, and it will be used in place of the built in authentication171callbacks.172173Let'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.175176We simply need to define a callback function that will be used to update the177Request object, right before it is dispatched.178179::180181 def pizza_auth(r, username):182 """Attaches HTTP Pizza Authentication to the given Request object.183 """184 r.headers['X-Pizza'] = username185186 return r187188Then, we can make a request using our Pizza Auth::189190 >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))191 <Response [200]>192193194Verbose Logging195---------------196197If you want to get a good look at what HTTP requests are being sent
8 unmodified lines
modified:docs/user/quickstart.rst+29 added
134 unmodified lines
135136 >>> r = requests.get(url, cookies=cookies)137 >>> r.content138 '{"cookies": {"cookies_are": "working"}}'139140141Basic Authentication142--------------------143144Most web services require authentication. There many different types of145authentication, but the most common is called HTTP Basic Auth.146147Making requests with Basic Auth is easy, with Requests::148149 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))150 <Response [200]>151152153Digest Authentication154---------------------155156Another popular form of protecting web service is Digest Authentication.157158Requests supports it!::159160 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'161 >>> requests.get(url, auth=('digest', 'user', 'pass'))162 <Response [200]>163164165-----------------------166167Ready for more? Check out the advanced_ section.
modified:requests/__init__.py+2 added-2 removed
13 unmodified lines
1415"""1617__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 lines
modified:requests/async.py+10 added-16 removed
26 unmodified lines
27 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'28)293031def _patched(f):31def patched(f):32 """Patches a given API function to not send."""3334 def wrapped(*args, **kwargs):35 return f(*args, return_response=False, **kwargs)3637 return wrapped383940def _send(r, pools=None):40def send(r, pools=None):41 """Sends a given Request object."""4243 if pools:44 r._pools = pools4546 r.send()4748 # Post-request hook.49 r = dispatch_hook('post_request', r.hooks, r)5051 # Response manipulation hook.52 r.response = dispatch_hook('response', r.hooks, r.response)5348 return r.response495051# Patched requests.api functions.58get = _patched(api.get)59head = _patched(api.head)60post = _patched(api.post)61put = _patched(api.put)62patch = _patched(api.patch)63delete = _patched(api.delete)64request = _patched(api.request)52get = patched(api.get)53head = patched(api.head)54post = patched(api.post)55put = patched(api.put)56patch = patched(api.patch)57delete = patched(api.delete)58request = patched(api.request)596061def map(requests, prefetch=True):62 """Concurrently converts a list of Requests to Responses.
1 unmodified line
64 :param requests: a collection of Request objects.65 :param prefetch: If False, the content will not be downloaded immediately.66 """6774 jobs = [gevent.spawn(_send, r) for r in requests]68 jobs = [gevent.spawn(send, r) for r in requests]69 gevent.joinall(jobs)7071 if prefetch:72 [r.response.content for r in requests]
6 unmodified lines
added:requests/auth.py+151 added
1# -*- coding: utf-8 -*-23"""4requests.auth5~~~~~~~~~~~~~67This module contains the authentication handlers for Requests.8"""910import time11import hashlib1213from base64 import b64encode14from urlparse import urlparse1516from .utils import randombytes, parse_dict_header171819def http_basic(r, username, password):20 """Attaches HTTP Basic Authentication to the given Request object.21 Arguments should be considered non-positional.2223 """24 username = str(username)25 password = str(password)2627 auth_s = b64encode('%s:%s' % (username, password))28 r.headers['Authorization'] = ('Basic %s' % auth_s)2930 return r313233def http_digest(r, username, password):34 """Attaches HTTP Digest Authentication to the given Request object.35 Arguments should be considered non-positional.36 """3738 def handle_401(r):39 """Takes the given response and tries digest-auth, if needed."""4041 s_auth = r.headers.get('www-authenticate', '')4243 if 'digest' in s_auth.lower():4445 last_nonce = ''46 nonce_count = 04748 chal = parse_dict_header(s_auth.replace('Digest ', ''))4950 realm = chal['realm']51 nonce = chal['nonce']52 qop = chal.get('qop')53 algorithm = chal.get('algorithm', 'MD5')54 opaque = chal.get('opaque', None)5556 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))6465 if H is None:66 return None6768 # XXX not implemented yet69 entdig = None70 path = urlparse(r.request.url).path7172 A1 = "%s:%s:%s" % (username, realm, password)73 A2 = "%s:%s" % (r.request.method, path)7475 if qop == 'auth':76 if nonce == last_nonce:77 nonce_count += 178 else:79 nonce_count = 180 last_nonce = nonce8182 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 None9495 # 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)105106107 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_code112113 # r.request.response114115 print locals()116117 print _r.headers118 return _r119120 return r121122 r.hooks['response'] = handle_401123 return r124125126def dispatch(t):127 """Given an auth tuple, return an expanded version."""128129 if not t:130 return t131 else:132 t = list(t)133134 # Make sure they're passing in something.135 assert len(t) >= 2136137 # If only two items are passed in, assume HTTPBasic.138 if (len(t) == 2):139 t.insert(0, 'basic')140141 # 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_digest147148 # Return a custom callable.149 return (t[0], tuple(t[1:]))150151
modified:requests/defaults.py+1 added-1 removed
23 unmodified lines
242526defaults['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}3031defaults['proxies'] = {}32defaults['verbose'] = None
6 unmodified lines
modified:requests/models.py+23 added-202 removed
14 unmodified lines
15from urllib2 import HTTPError16from urlparse import urlparse, urlunparse, urljoin17from datetime import datetime1819from .hooks import dispatch_hook20from .structures import CaseInsensitiveDict21from .packages.poster.encode import multipart_encode22from .packages.poster.streaminghttp import register_openers, get_handlers23from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)24from .status_codes import codes25from .exceptions import Timeout, URLRequired, TooManyRedirects26from .monkeys import Request as _Request26from .monkeys import (27 HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler,28 HTTPDigestAuthHandler, HTTPRedirectHandler)27from .monkeys import HTTPRedirectHandler2829from .auth import dispatch as auth_dispatch3031REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)3233
59 unmodified lines
93 #: :class:`Response <Response>` instance, containing94 #: content and metadata of HTTP Response, once :attr:`sent <send>`.95 self.response = Response()9697 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)99102 #: :class:`AuthObject` to attach to :class:`Request <Request>`.103 self.auth = auth104100 #: CookieJar to attach to :class:`Request <Request>`.101 self.cookies = cookies102103 #: Dictionary of configurations for this request.
15 unmodified lines
119 headers[k] = v120121 self.headers = headers122123 # Pre-request hook.124 r = dispatch_hook('pre_request', hooks, self)125 self.__dict__.update(r.__dict__)126127128 def __repr__(self):129 return '<Request [%s]>' % (self.method)130131
4 unmodified lines
136137 if self.cookies is not None:138 _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))139141 if self.auth:142 if not isinstance(self.auth.handler,143 (urllib2.AbstractBasicAuthHandler,144 urllib2.AbstractDigestAuthHandler)):145146 # TODO: REMOVE THIS COMPLETELY147 auth_manager.add_password(148 self.auth.realm, self.url,149 self.auth.username,150 self.auth.password)151152 self.auth.handler = self.auth.handler(auth_manager)153 auth_manager.add_auth(self.url, self.auth)154155 _handlers.append(self.auth.handler)156140 if self.proxies:141 _handlers.append(urllib2.ProxyHandler(self.proxies))142143 _handlers.append(HTTPRedirectHandler)
186 unmodified lines
330 else:331 data = self._enc_data332 headers = {}333334 if self.auth:335 auth_func, auth_args = self.auth336337 r = auth_func(self, *auth_args)338339 self.__dict__.update(r.__dict__)340341 # Build the Urllib2 Request.342 req = _Request(url, data=data, headers=headers, method=self.method)343344 # Add the headers to the request.
43 unmodified lines
388389390 self.sent = self.response.ok391392 # Response manipulation hook.393 self.response = dispatch_hook('response', self.hooks, self.response)394395 # Post-request hook.396 r = dispatch_hook('post_request', self.hooks, self)397 self.__dict__.update(r.__dict__)398399 return self.sent400401402class Response(object):
113 unmodified lines
516 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""517 if self.error:518 raise self.error519523524525class AuthManager(object):526 """Requests Authentication Manager."""527528 def __new__(cls):529 singleton = cls.__dict__.get('__singleton__')530 if singleton is not None:531 return singleton532533 cls.__singleton__ = singleton = object.__new__(cls)534535 return singleton536537538 def __init__(self):539 self.passwd = {}540 self._auth = {}541542543 def __repr__(self):544 return '<AuthManager [%s]>' % (self.method)545546547 def add_auth(self, uri, auth):548 """Registers AuthObject to AuthManager."""549550 uri = self.reduce_uri(uri, False)551552 # try to make it an AuthObject553 if not isinstance(auth, AuthObject):554 try:555 auth = AuthObject(*auth)556 except TypeError:557 pass558559 self._auth[uri] = auth560561562 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]567568 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])569570 if reduced_uri not in self.passwd:571 self.passwd[reduced_uri] = {}572 self.passwd[reduced_uri] = (user, passwd)573574575 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 authinfo581582 return (None, None)583584585 def get_auth(self, uri):586 (in_domain, in_path) = self.reduce_uri(uri, False)587588 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 authority594595596 def reduce_uri(self, uri, default_port=True):597 """Accept authority or URI and extract only the authority and path."""598599 # note HTTP URLs do not have a userinfo component600 parts = urllib2.urlparse.urlsplit(uri)601602 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 = '/'612613 host, port = urllib2.splitport(authority)614615 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)621622 return authority, path623624625 def is_suburi(self, base, test):626 """Check if test is below base in a URI tree627628 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 False638639640 def empty(self):641 self.passwd = {}642643644 def remove(self, uri, realm=None):645 # uri could be a single URI or a sequence646 if isinstance(uri, basestring):647 uri = [uri]648649 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]652653654 def __contains__(self, uri):655 # uri could be a single URI or a sequence656 if isinstance(uri, basestring):657 uri = [uri]658659 uri = tuple([self.reduce_uri(u, False) for u in uri])660661 if uri in self.passwd:662 return True663664 return False665666auth_manager = AuthManager()667668669670class 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.675676 :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 """681682 _handlers = {683 'basic': HTTPBasicAuthHandler,684 'forced_basic': HTTPForcedBasicAuthHandler,685 'digest': HTTPDigestAuthHandler,686 'proxy_basic': urllib2.ProxyBasicAuthHandler,687 'proxy_digest': urllib2.ProxyDigestAuthHandler688 }689690 def __init__(self, username, password, handler='forced_basic', realm=None):691 self.username = username692 self.password = password693 self.realm = realm694695 if isinstance(handler, basestring):696 self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)697 else:698 self.handler = handler
modified:requests/monkeys.py+5 added-114 removed
27 unmodified lines
282930class 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 pass3435 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 = _pass39373839class 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 = req59 self.retried = 06061 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(62 self, auth_header, host, req, headers63 )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)124 self.retried_req = None125126 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 pass131132 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.140141 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 raise
modified:requests/sessions.py+1 added-9 removed
110 unmodified lines
111 :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 lines
161 args = dispatch_hook('args', hooks, args)162163 r = Request(**args)164165 # Pre-request hook.166 r = dispatch_hook('pre_request', hooks, r)167165 # Don't send if asked nicely.166 if not return_response:167 return r168169 # Send the HTTP Request.170 r.send()171175 # Post-request hook.176 r = dispatch_hook('post_request', hooks, r)172178 # Response manipulation hook.179 r.response = dispatch_hook('response', hooks, r.response)180173 return r.response174175176 def get(self, url, **kwargs):
69 unmodified lines
modified:requests/utils.py+109 added
10 unmodified lines
1112import cgi13import codecs14import cookielib15import os16import random17import re18import zlib1920from urllib2 import parse_http_list as _parse_list_header212223# From mitsuhiko/werkzeug (used with permission).24def parse_list_header(value):25 """Parse lists as described by RFC 2068 Section 2.2627 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.3132 It basically works like :func:`parse_set_header` just that items33 may appear multiple times and case sensitivity is preserved.3435 The return value is a standard :class:`list`:3637 >>> parse_list_header('token, "quoted value"')38 ['token', 'quoted value']3940 To create a header from the :class:`list` again, use the41 :func:`dump_header` function.4243 :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 result525354# From mitsuhiko/werkzeug (used with permission).55def 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:5859 >>> 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')]6465 If there is no value for a key it will be `None`:6667 >>> parse_dict_header('key_without_value')68 {'key_without_value': None}6970 To create a header from the :class:`dict` again, use the71 :func:`dump_header` function.7273 :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 result868788# From mitsuhiko/werkzeug (used with permission).89def 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.9394 :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]102103 # 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 value111112113def header_expand(headers):114 """Returns an HTTP Header value string from a dictionary.115116 Example expansion::
39 unmodified lines
156 return ''.join(collector)157158159160def 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)173174175def dict_from_cookiejar(cj):176 """Returns a key/value dictionary from a CookieJar.177178 :param cj: CookieJar object to extract cookies from.
185 unmodified lines
modified:HISTORY.rst+8 added
1History2-------340.7.1 (2011-10-23)5++++++++++++++++++67* Move away from urllib2 authentication handling.8* Fully Remove AuthManager, AuthObject, &c.9* New tuple-based auth system with handler callbacks.1011120.7.0 (2011-10-22)13++++++++++++++++++1415* Sessions are now the primary interface.
198 unmodified lines
modified:test_requests.py+24 added-3 removed
137 unmodified lines
138 r = requests.patch(httpbin('patch'))139 self.assertEqual(r.status_code, 200)140141142 def test_AUTH_HTTP_200_OK_GET(self):142 def test_BASICAUTH_HTTP_200_OK_GET(self):143144 for service in SERVICES:145146 auth = ('user', 'pass')147 url = service('basic-auth', 'user', 'pass')148149 r = requests.get(url, auth=auth)150 # print r.__dict__150 self.assertEqual(r.status_code, 200)151153152 r = requests.get(url)153 self.assertEqual(r.status_code, 401)154155156 s = requests.session(auth=auth)157 r = s.get(url)158 self.assertEqual(r.status_code, 200)159160161 def test_DIGESTAUTH_HTTP_200_OK_GET(self):162163 for service in SERVICES:164165 auth = ('digest', 'user', 'pass')166 url = service('digest-auth', 'auth', 'user', 'pass')167168 r = requests.get(url, auth=auth)169 self.assertEqual(r.status_code, 200)170171 r = requests.get(url)172 self.assertEqual(r.status_code, 401)173174175 s = requests.session(auth=auth)176 r = s.get(url)177 self.assertEqual(r.status_code, 200)178179 def test_POSTBIN_GET_POST_FILES(self):180181 for service in SERVICES:182
351 unmodified lines