hrmm
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 55cea74 · Browse files · 3 files·+134 added−127 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+134 added−127 removed
- other:+134 added−127 removed
Provenance
- Commit
182f92a- Tree
63dad5f- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
55cea74
3 files changed+134 added−127 removed
modified:requests/core.py+1 added-1 removed
20 unmodified lines21 22 from api import *23 from config import settings24 from exceptions import *25-from models import HTTPError, Request, Response25+from models import Request, Response26 from sessions import session27 from status_codes import codes28 29 import utilsmodified:requests/models.py+68 added-126 removed
9 unmodified lines10 import urllib211 import socket12 import zlib13 14-15-from urllib2 import HTTPError14 from urlparse import urlparse, urlunparse, urljoin15 from datetime import datetime16 17 1 unmodified line19 # print dir(urllib3)20 21 from .config import settings22 from .structures import CaseInsensitiveDict25-from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip23+from .utils import *24 from .status_codes import codes25 from .exceptions import RequestException, Timeout, URLRequired, TooManyRedirects26 27 43 unmodified lines71 72 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})73 self.proxies = proxies74 77- self.data, self._enc_data = self._encode_params(data)78- self.params, self._enc_params = self._encode_params(params)75+ self.data = data76+ self._enc_data = encode_params(data)77+ self.params = params78+ self._enc_params = encode_params(params)79 80 #: :class:`Response <Response>` instance, containing81 #: content and metadata of HTTP Response, once :attr:`sent <send>`.82 self.response = Response()193 unmodified lines276 277 # Give Response some context.278 self.response.request = self279 280- @staticmethod281- def _encode_params(data):282- """Encode parameters in a piece of data.280 284- If the data supplied is a dictionary, encodes each parameter in it, and285- returns a list of tuples containing the encoded parameters, and a urlencoded286- version of that.281 288- Otherwise, assumes the data is already encoded appropriately, and289- returns it twice.290- """291-292- if hasattr(data, 'items'):293- result = []294- for k, vs in data.items():295- for v in isinstance(vs, list) and vs or [vs]:296- result.append((k.encode('utf-8') if isinstance(k, unicode) else k,297- v.encode('utf-8') if isinstance(v, unicode) else v)298- )299- return (result, urllib.urlencode(result, doseq=True))300-301- else:302- return data, data303-304- def _build_url(self):305- """Build the actual URL to use."""306-307- # Support for unicode domain names and paths.308- (scheme, netloc, path, params, query, fragment) = urlparse(self.url)309-310- # International Domain Name311- netloc = netloc.encode('idna')312-313- # Encode the path to to utf-8.314- if isinstance(path, unicode):315- path = path.encode('utf-8')316-317- # URL-encode the path.318- path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")319-320- # Turn it back into a bytestring.321- self.url = str(urlunparse([scheme, netloc, path, params, query, fragment]))322- self.url = str(urlunparse(323- [scheme, netloc, path, params, query, fragment]324- ))325-326- # Query Parameters?327- if self._enc_params:328-329- # If query parameters already exist in the URL, append.330- if urlparse(self.url).query:331- return '%s&%s' % (self.url, self._enc_params)332-333- # Otherwise, have at it.334- else:335- return '%s?%s' % (self.url, self._enc_params)336-337- else:338- # Kosher URL.339- return self.url340-282 def send(self, connection=None, anyway=False):283 """Sends the shit."""284 285 # Safety check.286 self._checks()287 288 # Build the final URL.348- url = self._build_url()289+ url = build_url(self.url, self.params)290 291+ print url292 # Setup Files.293 if self.files:294 pass295 12 unmodified lines308 309 try:310 # Create a new HTTP connection, since one wasn't passed in.311 if not connection:370- connection = urllib3.connection_from_url(url,371- timeout=self.timeout)312+ connection = urllib3.connection_from_url(url, timeout=self.timeout)313 314 # One-off request. Delay fetching the content until needed.315 do_block = False316 else:7 unmodified lines324 body=self.data,325 headers=self.headers,326 redirect=False,327 assert_same_host=False,328+ preload_content=do_block387- block=do_block329+ # block=do_block330 )331 332 # Extract cookies.333 # if self.cookiejar is not None:19 unmodified lines353 return self.sent354 355 356 415- def old_send(self, anyway=False):416- """Sends the request. Returns True of successful, false if not.417- If there was an HTTPError during transmission,418- self.response.status_code will contain the HTTPError code.357+ # def old_send(self, anyway=False):358+ # """Sends the request. Returns True of successful, false if not.359+ # If there was an HTTPError during transmission,360+ # self.response.status_code will contain the HTTPError code.361 420- Once a request is successfully sent, `sent` will equal True.362+ # Once a request is successfully sent, `sent` will equal True.363 422- :param anyway: If True, request will be sent, even if it has423- already been sent.424- """364+ # :param anyway: If True, request will be sent, even if it has365+ # already been sent.366+ # """367 426- self._checks()368+ # self._checks()369 428- # Logging429- if settings.verbose:430- settings.verbose.write('%s %s %s\n' % (431- datetime.now().isoformat(), self.method, self.url432- ))370+ # # Logging371+ # if settings.verbose:372+ # settings.verbose.write('%s %s %s\n' % (373+ # datetime.now().isoformat(), self.method, self.url374+ # ))375 434- url = self._build_url()435- if self.method in ('GET', 'HEAD', 'DELETE'):436- req = _Request(url, method=self.method)437- else:376+ # url = self._build_url()377+ # if self.method in ('GET', 'HEAD', 'DELETE'):378+ # req = _Request(url, method=self.method)379+ # else:380 439- if self.files:440- register_openers()381+ # if self.files:382+ # register_openers()383 442- if self.data:443- self.files.update(self.data)384+ # if self.data:385+ # self.files.update(self.data)386 445- datagen, headers = multipart_encode(self.files)446- req = _Request(url, data=datagen, headers=headers, method=self.method)387+ # datagen, headers = multipart_encode(self.files)388+ # req = _Request(url, data=datagen, headers=headers, method=self.method)389 448- else:449- req = _Request(url, data=self._enc_data, method=self.method)390+ # else:391+ # req = _Request(url, data=self._enc_data, method=self.method)392 451- if self.headers:452- for k, v in self.headers.iteritems():453- req.add_header(k, v)393+ # if self.headers:394+ # for k, v in self.headers.iteritems():395+ # req.add_header(k, v)396 455- if not self.sent or anyway:397+ # if not self.sent or anyway:398 457- try:458- opener = self._get_opener()459- try:399+ # try:400+ # opener = self._get_opener()401+ # try:402 461- resp = opener(req, timeout=self.timeout)403+ # resp = opener(req, timeout=self.timeout)404 463- except TypeError, err:464- # timeout argument is new since Python v2.6465- if not 'timeout' in str(err):466- raise405+ # except TypeError, err:406+ # # timeout argument is new since Python v2.6407+ # if not 'timeout' in str(err):408+ # raise409 468- if settings.timeout_fallback:469- # fall-back and use global socket timeout (This is not thread-safe!)470- old_timeout = socket.getdefaulttimeout()471- socket.setdefaulttimeout(self.timeout)410+ # if settings.timeout_fallback:411+ # # fall-back and use global socket timeout (This is not thread-safe!)412+ # old_timeout = socket.getdefaulttimeout()413+ # socket.setdefaulttimeout(self.timeout)414 473- resp = opener(req)415+ # resp = opener(req)416 475- if settings.timeout_fallback:476- # restore gobal timeout477- socket.setdefaulttimeout(old_timeout)417+ # if settings.timeout_fallback:418+ # # restore gobal timeout419+ # socket.setdefaulttimeout(old_timeout)420 479- if self.cookiejar is not None:480- self.cookiejar.extract_cookies(resp, req)421+ # if self.cookiejar is not None:422+ # self.cookiejar.extract_cookies(resp, req)423 482- except (urllib2.HTTPError, urllib2.URLError), why:483- if hasattr(why, 'reason'):484- if isinstance(why.reason, socket.timeout):485- why = Timeout(why)424+ # except (urllib2.HTTPError, urllib2.URLError), why:425+ # if hasattr(why, 'reason'):426+ # if isinstance(why.reason, socket.timeout):427+ # why = Timeout(why)428 487- self._build_response(why, is_error=True)429+ # self._build_response(why, is_error=True)430 489- else:490- self._build_response(resp)491- self.response.ok = True431+ # else:432+ # self._build_response(resp)433+ # self.response.ok = True434 493- self.sent = self.response.ok435+ # self.sent = self.response.ok436 495- return self.sent437+ # return self.sent438 439 440 class Response(object):441 """The core :class:`Response <Response>` object.288 unmodified linesmodified:requests/utils.py+65 added
11 unmodified lines12 import cgi13 import codecs14 import cookielib15 import re16+import urllib17 import zlib18+from urlparse import urlparse, urlunparse, urljoin19 20 21+def encode_params(params):22+ """Encode parameters in a piece of data.23+24+ If the data supplied is a dictionary, encodes each parameter in it, and25+ returns a list of tuples containing the encoded parameters, and a urlencoded26+ version of that.27+28+ Otherwise, assumes the data is already encoded appropriately, and29+ returns it twice.30+ """31+32+ if hasattr(params, 'items'):33+ result = []34+ for k, vs in params.items():35+ for v in isinstance(vs, list) and vs or [vs]:36+ result.append((k.encode('utf-8') if isinstance(k, unicode) else k,37+ v.encode('utf-8') if isinstance(v, unicode) else v)38+ )39+ return urllib.urlencode(result, doseq=True)40+41+ else:42+ return params43+44+def build_url(url, params):45+ """Build the actual URL to use."""46+47+48+ # Support for unicode domain names and paths.49+ (scheme, netloc, path, params, query, fragment) = urlparse(url)50+51+ # International Domain Name52+ netloc = netloc.encode('idna')53+54+ # Encode the path to to utf-8.55+ if isinstance(path, unicode):56+ path = path.encode('utf-8')57+58+ # URL-encode the path.59+ path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")60+61+ # Turn it back into a bytestring.62+ url = str(urlunparse([scheme, netloc, path, params, query, fragment]))63+ url = str(urlunparse(64+ [scheme, netloc, path, params, query, fragment]65+ ))66+67+ # Query Parameters?68+ if params:69+ params = encode_params(params)70+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+79+ else:80+ # Kosher URL.81+ return url82+83+84 def header_expand(headers):85 """Returns an HTTP Header value string from a dictionary.86 87 Example expansion::305 unmodified lines