Skip to content
Myr

PEP8fied all the things

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

I ran the pep8 checker (version 0.6.1) on the code base and tried to clean up as many pep8 errors as I could. Everything except line-width errors are gone (I was worried about messing up the documentor since I haven't fiddled with it).

authored by Michael Van Veen · committed by Michael Van Veen · parent 784b671 · Browse files · 11 files+74 added−80 removed
This commit

State

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

Diff stats

11 files+74 added−80 removed

  • other:+74 added−80 removed

11 files+74 added−80 removed

modified:requests/api.py+11 added-11 removed
52 unmodified lines
53 for k, v in headers.items() or {}:54 headers[k] = header_expand(v)5556 args = dict(57 method = method,58 url = url,59 data = data,60 params = params,61 headers = headers,62 cookiejar = cookies,63 files = files,64 auth = auth,65 timeout = timeout or config.settings.timeout,66 allow_redirects = allow_redirects,67 proxies = proxies or config.settings.proxies,57 method=method,58 url=url,59 data=data,60 params=params,61 headers=headers,62 cookiejar=cookies,63 files=files,64 auth=auth,65 timeout=timeout or config.settings.timeout,66 allow_redirects=allow_redirects,67 proxies=proxies or config.settings.proxies,68 )6970 # Arguments manipulation hook.71 args = dispatch_hook('args', hooks, args)
85 unmodified lines
modified:requests/config.py+15 added
4 unmodified lines
5~~~~~~~~~~~~~~~67This module provides the Requests settings feature set.89settings parameters:1011TODO: Verify!!!12TODO: Make sure format is acceptabl/cool13- :base_headers: - Sets default User-Agent to `python-requests.org`14- :accept_gzip: - Whether or not to accept gzip-compressed data15- :proxies: - http proxies?16- :verbose: - display verbose information?17- :timeout: - timeout time until request terminates18- :max_redirects: - maximum number of allowed redirects?19- :decode_unicode: - whether or not to accept unicode?2021Used globally2223"""242526class Settings(object):2728 def __init__(self, **kwargs):29 super(Settings, self).__init__()
17 unmodified lines
modified:requests/core.py+1 added-1 removed
24 unmodified lines
25from sessions import session26from status_codes import codes27from config import settings2829import utils29import utils
modified:requests/exceptions.py+7 added-1 removed
4 unmodified lines
5~~~~~~~~~~~~~~~67"""8910class RequestException(Exception):11 """There was an ambiguous exception that occured while handling your12 request."""131415class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15 171819class Timeout(RequestException):20 """The request timed out."""212223class URLRequired(RequestException):24 """A valid URL is required to make a request."""252627class InvalidMethod(RequestException):28 """An inappropriate method was attempted."""293031class TooManyRedirects(RequestException):32 """Too many redirects."""
modified:requests/models.py+21 added-42 removed
28 unmodified lines
2930REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31323333class Request(object):34 """The :class:`Request <Request>` object. It carries out all functionality of35 Requests. Recommended interface is with the Requests functions.36 """
57 unmodified lines
9495 #: True if Request has been sent.96 self.sent = False979998 # Header manipulation and defaults.99100 if settings.accept_gzip:101 settings.base_headers.update({'Accept-Encoding': 'gzip'})
8 unmodified lines
110 headers[k] = v111112 self.headers = headers113116114 def __repr__(self):115 return '<Request [%s]>' % (self.method)116120117 def _checks(self):118 """Deterministic checks for consistency."""119120 if not self.url:121 raise URLRequired122127123 def _get_opener(self):124 """Creates appropriate opener object for urllib2."""125126 _handlers = []
40 unmodified lines
167 opener.addheaders.remove((key, val))168169 return opener.open170176171 def _build_response(self, resp, is_error=False):172 """Build internal :class:`Response <Response>` object173 from given response.174 """175182176 def build(resp):177178 response = Response()179 response.status_code = getattr(resp, 'code', None)
5 unmodified lines
185 if self.cookiejar:186187 response.cookies = dict_from_cookiejar(self.cookiejar)188196189 except AttributeError:190 pass191192 if is_error:
2 unmodified lines
195 response.url = getattr(resp, 'url', None)196197 return response198207199 history = []200201 r = build(resp)202
45 unmodified lines
248249 self.response = r250 self.response.request = self251261252 @staticmethod253 def _encode_params(data):254 """Encode parameters in a piece of data.255
9 unmodified lines
265 result = []266 for k, vs in data.items():267 for v in isinstance(vs, list) and vs or [vs]:268 result.append((k.encode('utf-8') if isinstance(k, unicode) else k,279 v.encode('utf-8') if isinstance(v, unicode) else v))280 return result, urllib.urlencode(result, doseq=True)269 v.encode('utf-8') if isinstance(v, unicode) else v)270 )271 return (result, urllib.urlencode(result, doseq=True))272273 else:274 return data, data275284276 def _build_url(self):277 """Build the actual URL to use."""278279 # Support for unicode domain names and paths.280 scheme, netloc, path, params, query, fragment = urlparse(self.url)281 netloc = netloc.encode('idna')282283 if isinstance(path, unicode):284 path = path.encode('utf-8')285286 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")294 self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))287288 self.url = str(urlunparse(289 [scheme, netloc, path, params, query, fragment]290 ))291292 if self._enc_params:293 if urlparse(self.url).query:294 return '%s&%s' % (self.url, self._enc_params)295 else:296 return '%s?%s' % (self.url, self._enc_params)297 else:298 return self.url299304300 def send(self, anyway=False):301 """Sends the request. Returns True of successful, false if not.302 If there was an HTTPError during transmission,303 self.response.status_code will contain the HTTPError code.
11 unmodified lines
315 settings.verbose.write('%s %s %s\n' % (316 datetime.now().isoformat(), self.method, self.url317 ))318324319 url = self._build_url()320 if self.method in ('GET', 'HEAD', 'DELETE'):321 req = _Request(url, method=self.method)322 else:
10 unmodified lines
333 else:334 req = _Request(url, data=self._enc_data, method=self.method)335336 if self.headers:343 for k,v in self.headers.iteritems():337 for k, v in self.headers.iteritems():338 req.add_header(k, v)339340 if not self.sent or anyway:341
32 unmodified lines
374 else:375 self._build_response(resp)376 self.response.ok = True377384378 self.sent = self.response.ok379380 return self.sent381382383class Response(object):391 """The core :class:`Response <Response>` object. All392 :class:`Request <Request>` objects contain a393 :class:`response <Response>` attribute, which is an instance394 of this class.384 """The core :class:`Response <Response>` object.385386387 All :class:`Request <Request>` objects contain a :class:`response388 <Response>` attribute, which is an instance of this class.389 """390391 def __init__(self):392
30 unmodified lines
423424 #: A dictionary of Cookies the server sent back.425 self.cookies = None426433427 def __repr__(self):428 return '<Response [%s]>' % (self.status_code)429437430 def __nonzero__(self):431 """Returns true if :attr:`status_code` is 'OK'."""432433 return not self.error
53 unmodified lines
487488 self._content_consumed = True489 return self._content490499491 def raise_for_status(self):492 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""493 if self.error:494 raise self.error495496506497class AuthManager(object):498 """Requests Authentication Manager."""499500 def __new__(cls):
4 unmodified lines
505 cls.__singleton__ = singleton = object.__new__(cls)506507 return singleton508519509 def __init__(self):510 self.passwd = {}511 self._auth = {}512524513 def __repr__(self):514 return '<AuthManager [%s]>' % (self.method)515528516 def add_auth(self, uri, auth):517 """Registers AuthObject to AuthManager."""518519 uri = self.reduce_uri(uri, False)
6 unmodified lines
526 pass527528 self._auth[uri] = auth529543530 def add_password(self, realm, uri, user, passwd):531 """Adds password to AuthManager."""532 # uri could be a single URI or a sequence533 if isinstance(uri, basestring):
4 unmodified lines
538 if reduced_uri not in self.passwd:539 self.passwd[reduced_uri] = {}540 self.passwd[reduced_uri] = (user, passwd)541556542 def find_user_password(self, realm, authuri):543 for uris, authinfo in self.passwd.iteritems():544 reduced_authuri = self.reduce_uri(authuri, False)545 for uri in uris:
1 unmodified line
547 return authinfo548549 return (None, None)550566551 def get_auth(self, uri):552 (in_domain, in_path) = self.reduce_uri(uri, False)553554 for domain, path, authority in (
2 unmodified lines
557 if in_domain == domain:558 if path in in_path:559 return authority560577561 def reduce_uri(self, uri, default_port=True):562 """Accept authority or URI and extract only the authority and path."""563564 # note HTTP URLs do not have a userinfo component
20 unmodified lines
585 authority = "%s:%d" % (host, dport)586587 return authority, path588606589 def is_suburi(self, base, test):590 """Check if test is below base in a URI tree591592 Both args must be URIs in reduced form.
6 unmodified lines
599 if len(common) == len(base[1]):600 return True601 return False602621603 def empty(self):604 self.passwd = {}605625606 def remove(self, uri, realm=None):607 # uri could be a single URI or a sequence608 if isinstance(uri, basestring):609 uri = [uri]
1 unmodified line
611 for default_port in True, False:612 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])613 del self.passwd[reduced_uri][realm]614635615 def __contains__(self, uri):616 # uri could be a single URI or a sequence617 if isinstance(uri, basestring):618 uri = [uri]
7 unmodified lines
626627auth_manager = AuthManager()628629651630class AuthObject(object):653 """The :class:`AuthObject` is a simple HTTP Authentication token. When654 given to a Requests function, it enables Basic HTTP Authentication for that655 Request. You can also enable Authorization for domain realms with AutoAuth.656 See AutoAuth for more details.631 """The :class:`AuthObject` is a simple HTTP Authentication token.632633 When given to a Requests function, it enables Basic HTTP Authentication634 for that Request. You can also enable Authorization for domain realms635 with AutoAuth. See AutoAuth for more details.636637 :param username: Username to authenticate with.638 :param password: Password for given username.639 :param realm: (optional) the realm this auth applies to640 :param handler: (optional) basic || digest || proxy_basic || proxy_digest
19 unmodified lines
modified:requests/monkeys.py+4 added-10 removed
6 unmodified lines
7Urllib2 Monkey patches.89"""1011import urllib211import re12import urllib2131415class Request(urllib2.Request):16 """Hidden wrapper around the urllib2.Request object. Allows for manual17 setting of HTTP methods.18 """
16 unmodified lines
3536 http_error_302 = http_error_303 = http_error_307 = http_error_30137383839class 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 = 0464747 def reset_retry_count(self):48 # Python 2.6.5 will call this on 401 or 407 errors and thus loop49 # forever. We disable reset_retry_count completely and reset in50 # http_error_auth_reqed instead.51 pass525453 def http_error_auth_reqed(self, auth_header, host, req, headers):54 # Reset the retry counter once for each request.55 if req is not self.retried_req:56 self.retried_req = req
3 unmodified lines
60 self, auth_header, host, req, headers61 )62636664class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):65 """HTTP Basic Auth Handler with forced Authentication."""6667 auth_header = 'Authorization'68 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'69 'realm=(["\'])(.*?)\\2', re.I)7074 def __init__(self, *args, **kwargs):71 def __init__(self, *args, **kwargs):72 HTTPBasicAuthHandler.__init__(self, *args, **kwargs)737774 def http_error_401(self, req, fp, code, msg, headers):75 url = req.get_full_url()76 response = self._http_error_auth_reqed('www-authenticate', url, req, headers)77 self.reset_retry_count()78 return response7980 http_error_404 = http_error_401818682 def _http_error_auth_reqed(self, authreq, host, req, headers):8384 authreq = headers.get(authreq, None)85
24 unmodified lines
110 self.retried = 0111 return response112113119114class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):115116 def __init__(self, *args, **kwargs):117 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)
20 unmodified lines
138 except ValueError, inst:139 arg = inst.args[0]140 if arg.startswith("AbstractDigestAuthHandler doesn't know "):141 return148 raise142 raise
modified:requests/sessions.py+1 added-5 removed
13 unmodified lines
14from . import api15from .utils import add_dict_to_cookiejar16171818class Session(object):19 """A Requests session."""2021 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']222423 def __init__(self, **kwargs):2425 # Set up a CookieJar to be used by default26 self.cookies = cookielib.FileCookieJar()
4 unmodified lines
3132 # Map and wrap requests.api methods33 self._map_api_methods()343735 def __repr__(self):36 return '<requests-client at 0x%x>' % (id(self))3738 def __enter__(self):
2 unmodified lines
41 def __exit__(self, *args):42 # print args43 pass444845 def _map_api_methods(self):46 """Reads each available method from requests.api and decorates47 them with a wrapper, which inserts any instance-local attributes48 (from __attrs__) that have been set, combining them with **kwargs.
27 unmodified lines
7677def session(**kwargs):78 """Returns a :class:`Session` for context-managment."""7984 return Session(**kwargs)80 return Session(**kwargs)
modified:requests/status_codes.py+1 added-1 removed
78 unmodified lines
79for (code, titles) in _codes.items():80 for title in titles:81 setattr(codes, title, code)82 if not title.startswith('\\'):83 setattr(codes, title.upper(), code)83 setattr(codes, title.upper(), code)
modified:requests/structures.py+3 added-1 removed
6 unmodified lines
7Datastructures that power Requests.89"""101112class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary1415 For example, ``headers['content-encoding']`` will return the
30 unmodified lines
46 return self[key]47 else:48 return default495051class LookupDict(dict):52 """Dictionary lookup object."""5354 def __init__(self, name=None):
8 unmodified lines
6364 return self.__dict__.get(key, None)6566 def get(self, key, default=None):65 return self.__dict__.get(key, default)67 return self.__dict__.get(key, default)
modified:requests/utils.py+8 added-7 removed
49 unmodified lines
50 if len(params):5152 collector.append('; '.join(_params))5354 if not len(headers) == i+1:54 if not len(headers) == i + 1:55 collector.append(', ')565757 # Remove trailing seperators.58 if collector[-1] in (', ', '; '):59 del collector[-1]6061 return ''.join(collector)62636564def dict_from_cookiejar(cj):65 """Returns a key/value dictionary from a CookieJar.6667 :param cj: CookieJar object to extract cookies from.
164 unmodified lines
232233 :param content: bytestring to gzip-decode.234 """235238 return zlib.decompress(content, 16+zlib.MAX_WBITS)239 return zlib.decompress(content, 16+zlib.MAX_WBITS)236 return zlib.decompress(content, 16 + zlib.MAX_WBITS)237 return zlib.decompress(content, 16 + zlib.MAX_WBITS)238 return zlib.decompress(content, 16 + zlib.MAX_WBITS)239240241def stream_decode_gzip(iterator):242 """Stream decodes a gzip-encoded iterator"""
9 unmodified lines
252 yield rv253 except zlib.error:254 pass255256257def curl_from_request(request):258 """Returns a curl command from the request.259260 :param request: The :class:`Request <Request>` object
13 unmodified lines
274275 #: -u/--user - Specify the user name and password to use for server auth.276 #: Basic Auth only for now277 auth = ''278279 if request.auth is not None:280 auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)280281 auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)282283 method = ''284285 if request.method.upper() == 'HEAD':286 #: -I/--head - fetch headers only.287 method = '-I '288 else:
33 unmodified lines
322 form = "-d '%s' " % (request._enc_data)323324 #: Params handled in _build_url325 return curl + auth + method + header + cookies + form + '"' + request._build_url() + '"'324
modified:AUTHORS+2 added-1 removed
41 unmodified lines
42- Alejandro Giacometti43- Rick Mak44- Johan Bergström45- Josselin Jacquard46- Michael Van Veen <michael@mvanveen.net>47- Mike Waldner47- Serge Domkowski48- Serge Domkowski