Skip to content
Myr

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

3 files+134 added−127 removed

modified:requests/core.py+1 added-1 removed
20 unmodified lines
2122from api import *23from config import settings24from exceptions import *25from models import HTTPError, Request, Response25from models import Request, Response26from sessions import session27from status_codes import codes2829import utils
modified:requests/models.py+68 added-126 removed
9 unmodified lines
10import urllib211import socket12import zlib131415from urllib2 import HTTPError14from urlparse import urlparse, urlunparse, urljoin15from datetime import datetime1617
1 unmodified line
19# print dir(urllib3)2021from .config import settings22from .structures import CaseInsensitiveDict25from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip23from .utils import *24from .status_codes import codes25from .exceptions import RequestException, Timeout, URLRequired, TooManyRedirects2627
43 unmodified lines
7172 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})73 self.proxies = proxies7477 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)7980 #: :class:`Response <Response>` instance, containing81 #: content and metadata of HTTP Response, once :attr:`sent <send>`.82 self.response = Response()
193 unmodified lines
276277 # Give Response some context.278 self.response.request = self279280 @staticmethod281 def _encode_params(data):282 """Encode parameters in a piece of data.280284 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.281288 Otherwise, assumes the data is already encoded appropriately, and289 returns it twice.290 """291292 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))300301 else:302 return data, data303304 def _build_url(self):305 """Build the actual URL to use."""306307 # Support for unicode domain names and paths.308 (scheme, netloc, path, params, query, fragment) = urlparse(self.url)309310 # International Domain Name311 netloc = netloc.encode('idna')312313 # Encode the path to to utf-8.314 if isinstance(path, unicode):315 path = path.encode('utf-8')316317 # URL-encode the path.318 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")319320 # 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 ))325326 # Query Parameters?327 if self._enc_params:328329 # If query parameters already exist in the URL, append.330 if urlparse(self.url).query:331 return '%s&%s' % (self.url, self._enc_params)332333 # Otherwise, have at it.334 else:335 return '%s?%s' % (self.url, self._enc_params)336337 else:338 # Kosher URL.339 return self.url340282 def send(self, connection=None, anyway=False):283 """Sends the shit."""284285 # Safety check.286 self._checks()287288 # Build the final URL.348 url = self._build_url()289 url = build_url(self.url, self.params)290291 print url292 # Setup Files.293 if self.files:294 pass295
12 unmodified lines
308309 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)313314 # One-off request. Delay fetching the content until needed.315 do_block = False316 else:
7 unmodified lines
324 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 )331332 # Extract cookies.333 # if self.cookiejar is not None:
19 unmodified lines
353 return self.sent354355356415 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.361420 Once a request is successfully sent, `sent` will equal True.362 # Once a request is successfully sent, `sent` will equal True.363422 :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 # """367426 self._checks()368 # self._checks()369428 # 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 # ))375434 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:380439 if self.files:440 register_openers()381 # if self.files:382 # register_openers()383442 if self.data:443 self.files.update(self.data)384 # if self.data:385 # self.files.update(self.data)386445 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)389448 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)392451 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)396455 if not self.sent or anyway:397 # if not self.sent or anyway:398457 try:458 opener = self._get_opener()459 try:399 # try:400 # opener = self._get_opener()401 # try:402461 resp = opener(req, timeout=self.timeout)403 # resp = opener(req, timeout=self.timeout)404463 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 # raise409468 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)414473 resp = opener(req)415 # resp = opener(req)416475 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)420479 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)423482 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)428487 self._build_response(why, is_error=True)429 # self._build_response(why, is_error=True)430489 else:490 self._build_response(resp)491 self.response.ok = True431 # else:432 # self._build_response(resp)433 # self.response.ok = True434493 self.sent = self.response.ok435 # self.sent = self.response.ok436495 return self.sent437 # return self.sent438439440class Response(object):441 """The core :class:`Response <Response>` object.
288 unmodified lines
modified:requests/utils.py+65 added
11 unmodified lines
12import cgi13import codecs14import cookielib15import re16import urllib17import zlib18from urlparse import urlparse, urlunparse, urljoin192021def encode_params(params):22 """Encode parameters in a piece of data.2324 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.2728 Otherwise, assumes the data is already encoded appropriately, and29 returns it twice.30 """3132 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)4041 else:42 return params4344def build_url(url, params):45 """Build the actual URL to use."""464748 # Support for unicode domain names and paths.49 (scheme, netloc, path, params, query, fragment) = urlparse(url)5051 # International Domain Name52 netloc = netloc.encode('idna')5354 # Encode the path to to utf-8.55 if isinstance(path, unicode):56 path = path.encode('utf-8')5758 # URL-encode the path.59 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")6061 # 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 ))6667 # Query Parameters?68 if params:69 params = encode_params(params)7071 # 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)7879 else:80 # Kosher URL.81 return url828384def header_expand(headers):85 """Returns an HTTP Header value string from a dictionary.8687 Example expansion::
305 unmodified lines