Skip to content
Myr

fix

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 · parent 0b22bc9 · Browse files · 2 files+48 added−252 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+48 added−252 removed

  • other:+48 added−252 removed

2 files+48 added−252 removed

modified:requests/models.py+35 added-226 removed
79 unmodified lines
80 #: :class:`Response <Response>` instance, containing81 #: content and metadata of HTTP Response, once :attr:`sent <send>`.82 self.response = Response()8384 if isinstance(auth, (list, tuple)):85 auth = AuthObject(*auth)86 if not auth:87 auth = auth_manager.get_auth(self.url)84 # if isinstance(auth, (list, tuple)):85 # auth = AuthObject(*auth)86 # if not auth:87 # auth = auth_manager.get_auth(self.url)8889 #: :class:`AuthObject` to attach to :class:`Request <Request>`.90 self.auth = auth90 # self.auth = auth9192 #: CookieJar to attach to :class:`Request <Request>`.93 self.cookies = cookies94
84 unmodified lines
179 response.status_code = getattr(resp, 'status', None)180181 try:182 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))183 response.raw = resp._raw183 response.raw = resp184 # print dir(self.response.raw)185 # print self186187 # print (response.raw)188 # print dir(response.raw)189 # print response.raw.sock.read()190 # print '------'191192193 # if self.cookiejar:194195 # response.cookies = dict_from_cookiejar(self.cookiejar)196
133 unmodified lines
330 body=self.data,331 headers=self.headers,332 redirect=False,333 assert_same_host=False,334 # preload_content=True326 preload_content=do_block335 preload_content=False336 # block=do_block337 )338339 # Extract cookies.
10 unmodified lines
350 print 'FUCK'351 print why352353 else:354 # self.response = Response.from_urllib3()355 self._build_response(r)356 self.response.ok = True357358
1 unmodified line
360361 return self.sent362363354355 # def old_send(self, anyway=False):356 # """Sends the request. Returns True of successful, false if not.357 # If there was an HTTPError during transmission,358 # self.response.status_code will contain the HTTPError code.359360 # Once a request is successfully sent, `sent` will equal True.361362 # :param anyway: If True, request will be sent, even if it has363 # already been sent.364 # """365366 # self._checks()367368 # # Logging369 # if settings.verbose:370 # settings.verbose.write('%s %s %s\n' % (371 # datetime.now().isoformat(), self.method, self.url372 # ))373374 # url = self._build_url()375 # if self.method in ('GET', 'HEAD', 'DELETE'):376 # req = _Request(url, method=self.method)377 # else:378379 # if self.files:380 # register_openers()381382 # if self.data:383 # self.files.update(self.data)384385 # datagen, headers = multipart_encode(self.files)386 # req = _Request(url, data=datagen, headers=headers, method=self.method)387388 # else:389 # req = _Request(url, data=self._enc_data, method=self.method)390391 # if self.headers:392 # for k, v in self.headers.iteritems():393 # req.add_header(k, v)394395 # if not self.sent or anyway:396397 # try:398 # opener = self._get_opener()399 # try:400401 # resp = opener(req, timeout=self.timeout)402403 # except TypeError, err:404 # # timeout argument is new since Python v2.6405 # if not 'timeout' in str(err):406 # raise407408 # if settings.timeout_fallback:409 # # fall-back and use global socket timeout (This is not thread-safe!)410 # old_timeout = socket.getdefaulttimeout()411 # socket.setdefaulttimeout(self.timeout)412413 # resp = opener(req)414415 # if settings.timeout_fallback:416 # # restore gobal timeout417 # socket.setdefaulttimeout(old_timeout)418419 # if self.cookiejar is not None:420 # self.cookiejar.extract_cookies(resp, req)421422 # except (urllib2.HTTPError, urllib2.URLError), why:423 # if hasattr(why, 'reason'):424 # if isinstance(why.reason, socket.timeout):425 # why = Timeout(why)426427 # self._build_response(why, is_error=True)428429 # else:430 # self._build_response(resp)431 # self.response.ok = True432433 # self.sent = self.response.ok434435 # return self.sent436437364class Response(object):365 """The core :class:`Response <Response>` object.366367
58 unmodified lines
426 if not chunk:427 break428 yield chunk429 self._content_consumed = True504 gen = generate()430 gen = generate431432 if 'gzip' in self.headers.get('content-encoding', ''):433 gen = stream_decode_gzip(gen)434435 if decode_unicode is None:436 decode_unicode = settings.decode_unicode437438 if decode_unicode:439 gen = stream_decode_response_unicode(gen, self)440441 return gen442443444 @property
10 unmodified lines
455 'The content for this response was already consumed')456457 # Read the contents.458 # print self.raw.__dict__459460 # print461 # print '~'462 # # print self.raw463 # print self.raw.getresponse()464 # print dir(self.raw)465 # print466 # print467 # print468469 # self.raw.read() or529 self._content = self.raw.read() or self._response.data470 self._content = self.raw.read()471 # print self.raw.__dict__472473 # Decode GZip'd content.474 if 'gzip' in self.headers.get('content-encoding', ''):
8 unmodified lines
483484 self._content_consumed = True485 return self._content486487488 def raise_for_status(self):489 """Raises stored :class:`HTTPError` or :class:`URLError`,490 if one occured.491 """
11 unmodified lines
503 elif (self.status_code >= 500) and (self.status_code < 600):504 raise Exception('500 yo')505506565class AuthManager(object):566 """Requests Authentication Manager."""567568 def __new__(cls):569 singleton = cls.__dict__.get('__singleton__')570 if singleton is not None:571 return singleton572573 cls.__singleton__ = singleton = object.__new__(cls)574575 return singleton576577 def __init__(self):578 self.passwd = {}579 self._auth = {}580581 def __repr__(self):582 return '<AuthManager [%s]>' % (self.method)583584 def add_auth(self, uri, auth):585 """Registers AuthObject to AuthManager."""586587 uri = self.reduce_uri(uri, False)588589 # try to make it an AuthObject590 if not isinstance(auth, AuthObject):591 try:592 auth = AuthObject(*auth)593 except TypeError:594 pass595596 self._auth[uri] = auth597598 def add_password(self, realm, uri, user, passwd):599 """Adds password to AuthManager."""600 # uri could be a single URI or a sequence601 if isinstance(uri, basestring):602 uri = [uri]603604 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])605606 if reduced_uri not in self.passwd:607 self.passwd[reduced_uri] = {}608 self.passwd[reduced_uri] = (user, passwd)609610 def find_user_password(self, realm, authuri):611 for uris, authinfo in self.passwd.iteritems():612 reduced_authuri = self.reduce_uri(authuri, False)613 for uri in uris:614 if self.is_suburi(uri, reduced_authuri):615 return authinfo616617 return (None, None)618619 def get_auth(self, uri):620 (in_domain, in_path) = self.reduce_uri(uri, False)621622 for domain, path, authority in (623 (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()624 ):625 if in_domain == domain:626 if path in in_path:627 return authority628629 def reduce_uri(self, uri, default_port=True):630 """Accept authority or URI and extract only the authority and path."""631632 # note HTTP URLs do not have a userinfo component633 parts = urllib2.urlparse.urlsplit(uri)634635 if parts[1]:636 # URI637 scheme = parts[0]638 authority = parts[1]639 path = parts[2] or '/'640 else:641 # host or host:port642 scheme = None643 authority = uri644 path = '/'645646 host, port = urllib2.splitport(authority)647648 if default_port and port is None and scheme is not None:649 dport = {"http": 80,650 "https": 443,651 }.get(scheme)652 if dport is not None:653 authority = "%s:%d" % (host, dport)654655 return authority, path656657 def is_suburi(self, base, test):658 """Check if test is below base in a URI tree659660 Both args must be URIs in reduced form.661 """662 if base == test:663 return True664 if base[0] != test[0]:665 return False666 common = urllib2.posixpath.commonprefix((base[1], test[1]))667 if len(common) == len(base[1]):668 return True669 return False670671 def empty(self):672 self.passwd = {}673674 def remove(self, uri, realm=None):675 # uri could be a single URI or a sequence676 if isinstance(uri, basestring):677 uri = [uri]678679 for default_port in True, False:680 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])681 del self.passwd[reduced_uri][realm]682683 def __contains__(self, uri):684 # uri could be a single URI or a sequence685 if isinstance(uri, basestring):686 uri = [uri]687688 uri = tuple([self.reduce_uri(u, False) for u in uri])689690 if uri in self.passwd:691 return True692693 return False694695auth_manager = AuthManager()696697507class AuthObject(object):508 """The :class:`AuthObject` is a simple HTTP Authentication token.509510 When given to a Requests function, it enables Basic HTTP Authentication
26 unmodified lines
modified:requests/utils.py+13 added-26 removed
39 unmodified lines
4041 else:42 return params434444def build_url(url, params):45def build_url(url, query_params):46 """Build the actual URL to use."""474748 # Support for unicode domain names and paths.49 (scheme, netloc, path, params, query, fragment) = urlparse(url)5051 # International Domain Name49 scheme, netloc, path, params, query, fragment = urlparse(url)50 netloc = netloc.encode('idna')5154 # Encode the path to to utf-8.52 if isinstance(path, unicode):56 path = path.encode('utf-8')53 path = path.encode('utf-8')5458 # URL-encode the path.55 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")5661 # Turn it back into a bytestring.62 url = str(urlunparse([scheme, netloc, path, params, query, fragment]))57 url = str(urlunparse(64 [scheme, netloc, path, params, query, fragment]65 ))58 [scheme, netloc, path, params, query, fragment]59 ))6067 # Query Parameters?68 if params:69 params = encode_params(params)61 query_params = encode_params(query_params)6271 # If query parameters already exist in the URL, append.72 if urlparse(url).query:73 return '%s&%s' % (url, params)7475 # Otherwise, have at it.76 else:77 return '%s?%s' % (url, params)7863 if query_params:64 if urlparse(url).query:65 return '%s&%s' % (url, query_params)66 else:67 return '%s?%s' % (url, query_params)68 else:80 # Kosher URL.81 return url69 return url707172def header_expand(headers):73 """Returns an HTTP Header value string from a dictionary.
50 unmodified lines
124125 for _, cookies in cj._cookies.items():126 for _, cookies in cookies.items():127 for cookie in cookies.values():140 # print cookie128 cookie_dict[cookie.name] = cookie.value129130 return cookie_dict131
248 unmodified lines