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
Provenance
- Commit
5287b8c- Tree
0a40d4d- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
0b22bc9
2 files changed+48 added−252 removed
modified:requests/models.py+35 added-226 removed
79 unmodified lines80 #: :class:`Response <Response>` instance, containing81 #: content and metadata of HTTP Response, once :attr:`sent <send>`.82 self.response = Response()83 84- 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)88 89 #: :class:`AuthObject` to attach to :class:`Request <Request>`.90- self.auth = auth90+ # self.auth = auth91 92 #: CookieJar to attach to :class:`Request <Request>`.93 self.cookies = cookies94 84 unmodified lines179 response.status_code = getattr(resp, 'status', None)180 181 try:182 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))183- response.raw = resp._raw183+ response.raw = resp184+ # print dir(self.response.raw)185+ # print self186 187+ # print (response.raw)188+ # print dir(response.raw)189+ # print response.raw.sock.read()190+ # print '------'191+192+193 # if self.cookiejar:194 195 # response.cookies = dict_from_cookiejar(self.cookiejar)196 133 unmodified lines330 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 )338 339 # Extract cookies.10 unmodified lines350 print 'FUCK'351 print why352 353 else:354+ # self.response = Response.from_urllib3()355 self._build_response(r)356 self.response.ok = True357 358 1 unmodified line360 361 return self.sent362 363 354-355- # 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.359-360- # Once a request is successfully sent, `sent` will equal True.361-362- # :param anyway: If True, request will be sent, even if it has363- # already been sent.364- # """365-366- # self._checks()367-368- # # Logging369- # if settings.verbose:370- # settings.verbose.write('%s %s %s\n' % (371- # datetime.now().isoformat(), self.method, self.url372- # ))373-374- # url = self._build_url()375- # if self.method in ('GET', 'HEAD', 'DELETE'):376- # req = _Request(url, method=self.method)377- # else:378-379- # if self.files:380- # register_openers()381-382- # if self.data:383- # self.files.update(self.data)384-385- # datagen, headers = multipart_encode(self.files)386- # req = _Request(url, data=datagen, headers=headers, method=self.method)387-388- # else:389- # req = _Request(url, data=self._enc_data, method=self.method)390-391- # if self.headers:392- # for k, v in self.headers.iteritems():393- # req.add_header(k, v)394-395- # if not self.sent or anyway:396-397- # try:398- # opener = self._get_opener()399- # try:400-401- # resp = opener(req, timeout=self.timeout)402-403- # except TypeError, err:404- # # timeout argument is new since Python v2.6405- # if not 'timeout' in str(err):406- # raise407-408- # 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)412-413- # resp = opener(req)414-415- # if settings.timeout_fallback:416- # # restore gobal timeout417- # socket.setdefaulttimeout(old_timeout)418-419- # if self.cookiejar is not None:420- # self.cookiejar.extract_cookies(resp, req)421-422- # except (urllib2.HTTPError, urllib2.URLError), why:423- # if hasattr(why, 'reason'):424- # if isinstance(why.reason, socket.timeout):425- # why = Timeout(why)426-427- # self._build_response(why, is_error=True)428-429- # else:430- # self._build_response(resp)431- # self.response.ok = True432-433- # self.sent = self.response.ok434-435- # return self.sent436-437-364 class Response(object):365 """The core :class:`Response <Response>` object.366 367 58 unmodified lines426 if not chunk:427 break428 yield chunk429 self._content_consumed = True504- gen = generate()430+ gen = generate431+432 if 'gzip' in self.headers.get('content-encoding', ''):433 gen = stream_decode_gzip(gen)434+435 if decode_unicode is None:436 decode_unicode = settings.decode_unicode437+438 if decode_unicode:439 gen = stream_decode_response_unicode(gen, self)440+441 return gen442 443 444 @property10 unmodified lines455 'The content for this response was already consumed')456 457 # Read the contents.458 # print self.raw.__dict__459+460+ # print461+ # print '~'462+ # # print self.raw463+ # print self.raw.getresponse()464+ # print dir(self.raw)465+ # print466+ # print467+ # print468+469+ # self.raw.read() or529- self._content = self.raw.read() or self._response.data470+ self._content = self.raw.read()471 # print self.raw.__dict__472 473 # Decode GZip'd content.474 if 'gzip' in self.headers.get('content-encoding', ''):8 unmodified lines483 484 self._content_consumed = True485 return self._content486 487+488 def raise_for_status(self):489 """Raises stored :class:`HTTPError` or :class:`URLError`,490 if one occured.491 """11 unmodified lines503 elif (self.status_code >= 500) and (self.status_code < 600):504 raise Exception('500 yo')505 506 565-class AuthManager(object):566- """Requests Authentication Manager."""567-568- def __new__(cls):569- singleton = cls.__dict__.get('__singleton__')570- if singleton is not None:571- return singleton572-573- cls.__singleton__ = singleton = object.__new__(cls)574-575- return singleton576-577- def __init__(self):578- self.passwd = {}579- self._auth = {}580-581- def __repr__(self):582- return '<AuthManager [%s]>' % (self.method)583-584- def add_auth(self, uri, auth):585- """Registers AuthObject to AuthManager."""586-587- uri = self.reduce_uri(uri, False)588-589- # try to make it an AuthObject590- if not isinstance(auth, AuthObject):591- try:592- auth = AuthObject(*auth)593- except TypeError:594- pass595-596- self._auth[uri] = auth597-598- 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]603-604- reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])605-606- if reduced_uri not in self.passwd:607- self.passwd[reduced_uri] = {}608- self.passwd[reduced_uri] = (user, passwd)609-610- 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 authinfo616-617- return (None, None)618-619- def get_auth(self, uri):620- (in_domain, in_path) = self.reduce_uri(uri, False)621-622- 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 authority628-629- def reduce_uri(self, uri, default_port=True):630- """Accept authority or URI and extract only the authority and path."""631-632- # note HTTP URLs do not have a userinfo component633- parts = urllib2.urlparse.urlsplit(uri)634-635- 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 = '/'645-646- host, port = urllib2.splitport(authority)647-648- 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)654-655- return authority, path656-657- def is_suburi(self, base, test):658- """Check if test is below base in a URI tree659-660- 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 False670-671- def empty(self):672- self.passwd = {}673-674- def remove(self, uri, realm=None):675- # uri could be a single URI or a sequence676- if isinstance(uri, basestring):677- uri = [uri]678-679- 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]682-683- def __contains__(self, uri):684- # uri could be a single URI or a sequence685- if isinstance(uri, basestring):686- uri = [uri]687-688- uri = tuple([self.reduce_uri(u, False) for u in uri])689-690- if uri in self.passwd:691- return True692-693- return False694-695-auth_manager = AuthManager()696-697-507 class AuthObject(object):508 """The :class:`AuthObject` is a simple HTTP Authentication token.509 510 When given to a Requests function, it enables Basic HTTP Authentication26 unmodified linesmodified:requests/utils.py+13 added-26 removed
39 unmodified lines40 41 else:42 return params43 44+44-def build_url(url, params):45+def build_url(url, query_params):46 """Build the actual URL to use."""47 47-48 # Support for unicode domain names and paths.49- (scheme, netloc, path, params, query, fragment) = urlparse(url)50-51- # International Domain Name49+ scheme, netloc, path, params, query, fragment = urlparse(url)50 netloc = netloc.encode('idna')51 54- # Encode the path to to utf-8.52 if isinstance(path, unicode):56- path = path.encode('utf-8')53+ path = path.encode('utf-8')54 58- # URL-encode the path.55 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")56 61- # 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+ ))60 67- # Query Parameters?68- if params:69- params = encode_params(params)61+ query_params = encode_params(query_params)62 71- # If query parameters already exist in the URL, append.72- if urlparse(url).query:73- return '%s&%s' % (url, params)74-75- # Otherwise, have at it.76- else:77- return '%s?%s' % (url, params)78-63+ 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 url70 71 72 def header_expand(headers):73 """Returns an HTTP Header value string from a dictionary.50 unmodified lines124 125 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.value129 130 return cookie_dict131 248 unmodified lines