diff options
| author | ianb <devnull@localhost> | 2006-10-20 22:08:05 +0000 |
|---|---|---|
| committer | ianb <devnull@localhost> | 2006-10-20 22:08:05 +0000 |
| commit | 44fa5352360b78696c3d81cafa8e24eaa4f6c3ed (patch) | |
| tree | ccde2c446f352cb5344f3c9a40090f12290bf9a7 | |
| parent | 9eadab4b64440958f99a2fa1798227bb4a53193c (diff) | |
| download | paste-44fa5352360b78696c3d81cafa8e24eaa4f6c3ed.tar.gz | |
A big commit, primarily aesthetic/whitespace in nature. This is the result of running pylint over the codebase. Some minor/hard-to-reach typos were also picked up.
36 files changed, 204 insertions, 182 deletions
diff --git a/paste/auth/basic.py b/paste/auth/basic.py index 1a91e04..c51dde5 100644 --- a/paste/auth/basic.py +++ b/paste/auth/basic.py @@ -41,11 +41,11 @@ class AuthBasicAuthenticator: authorization = AUTHORIZATION(environ) if not authorization: return self.build_authentication() - (authmeth, auth) = authorization.split(' ',1) + (authmeth, auth) = authorization.split(' ', 1) if 'basic' != authmeth.lower(): return self.build_authentication() auth = auth.strip().decode('base64') - username, password = auth.split(':',1) + username, password = auth.split(':', 1) if self.authfunc(environ, username, password): return username return self.build_authentication() diff --git a/paste/auth/cas.py b/paste/auth/cas.py index 6e501b5..c3521a0 100644 --- a/paste/auth/cas.py +++ b/paste/auth/cas.py @@ -66,7 +66,7 @@ def AuthCASHandler(application, authority): qs = environ.get('QUERY_STRING','').split("&") if qs and qs[-1].startswith("ticket="): # assume a response from the authority - ticket = qs.pop().split("=",1)[1] + ticket = qs.pop().split("=", 1)[1] environ['QUERY_STRING'] = "&".join(qs) service = construct_url(environ) args = urllib.urlencode( diff --git a/paste/auth/cookie.py b/paste/auth/cookie.py index df63329..a650436 100644 --- a/paste/auth/cookie.py +++ b/paste/auth/cookie.py @@ -41,22 +41,23 @@ corresponding to a database session id) is stored in the cookie. """ -import sha, hmac, base64, random, time, string, warnings +import sha, hmac, base64, random, time, warnings from paste.request import get_cookies def make_time(value): - return time.strftime("%Y%m%d%H%M",time.gmtime(value)) -_signature_size = len(hmac.new('x','x',sha).digest()) + return time.strftime("%Y%m%d%H%M", time.gmtime(value)) +_signature_size = len(hmac.new('x', 'x', sha).digest()) _header_size = _signature_size + len(make_time(time.time())) # @@: Should this be using urllib.quote? # build encode/decode functions to safely pack away values -_encode = [('\\','\\x5c'),('"','\\x22'),('=','\\x3d'),(';','\\x3b')] -_decode = [(v,k) for (k,v) in _encode] +_encode = [('\\', '\\x5c'), ('"', '\\x22'), + ('=', '\\x3d'), (';', '\\x3b')] +_decode = [(v, k) for (k, v) in _encode] _decode.reverse() def encode(s, sublist = _encode): - return reduce((lambda a,(b,c): string.replace(a,b,c)), sublist, str(s)) -decode = lambda s: encode(s,_decode) + return reduce((lambda a, (b, c): a.replace(b, c)), sublist, str(s)) +decode = lambda s: encode(s, _decode) class CookieTooLarge(RuntimeError): def __init__(self, content, cookie): @@ -64,10 +65,10 @@ class CookieTooLarge(RuntimeError): self.content = content self.cookie = cookie -_all_chars = ''.join([chr(x) for x in range(0,255)]) +_all_chars = ''.join([chr(x) for x in range(0, 255)]) def new_secret(): """ returns a 64 byte secret """ - return ''.join(random.sample(_all_chars,64)) + return ''.join(random.sample(_all_chars, 64)) class AuthCookieSigner: """ @@ -131,24 +132,24 @@ class AuthCookieSigner: cookie is handled server-side in the auth() function. """ cookie = base64.b64encode( - hmac.new(self.secret,content,sha).digest() + - make_time(time.time()+60*self.timeout) + - content).replace("/","_").replace("=","~") + hmac.new(self.secret, content, sha).digest() + + make_time(time.time() + 60*self.timeout) + + content).replace("/", "_").replace("=", "~") if len(cookie) > self.maxlen: - raise CookieTooLarge(content,cookie) + raise CookieTooLarge(content, cookie) return cookie - def auth(self,cookie): + def auth(self, cookie): """ Authenticate the cooke using the signature, verify that it has not expired; and return the cookie's content """ decode = base64.b64decode( - cookie.replace("_","/").replace("~","=")) + cookie.replace("_", "/").replace("~", "=")) signature = decode[:_signature_size] expires = decode[_signature_size:_header_size] content = decode[_header_size:] - if signature == hmac.new(self.secret,content,sha).digest(): + if signature == hmac.new(self.secret, content, sha).digest(): if int(expires) > int(make_time(time.time())): return content else: @@ -177,7 +178,7 @@ class AuthCookieEnviron(list): def append(self, value): if value in self: return - list.append(self,str(value)) + list.append(self, str(value)) class AuthCookieHandler: """ @@ -238,7 +239,7 @@ class AuthCookieHandler: def __init__(self, application, cookie_name=None, scanlist=None, signer=None, secret=None, timeout=None, maxlen=None): if not signer: - signer = self.signer_class(secret,timeout,maxlen) + signer = self.signer_class(secret, timeout, maxlen) self.signer = signer self.scanlist = scanlist or ('REMOTE_USER','REMOTE_SESSION') self.application = application @@ -247,13 +248,13 @@ class AuthCookieHandler: def __call__(self, environ, start_response): if self.environ_name in environ: raise AssertionError("AuthCookie already installed!") - scanlist = self.environ_class(self,self.scanlist) + scanlist = self.environ_class(self, self.scanlist) jar = get_cookies(environ) if jar.has_key(self.cookie_name): content = self.signer.auth(jar[self.cookie_name].value) if content: for pair in content.split(";"): - (k,v) = pair.split("=") + (k, v) = pair.split("=") k = decode(k) if k not in scanlist: scanlist.append(k) @@ -275,24 +276,24 @@ class AuthCookieHandler: pack up their values, signs the content and issues a cookie. """ scanlist = environ.get(self.environ_name) - assert scanlist and isinstance(scanlist,self.environ_class) + assert scanlist and isinstance(scanlist, self.environ_class) content = [] for k in scanlist: - v = environ.get(k,None) + v = environ.get(k) if v is not None: if type(v) is not str: raise ValueError( "The value of the environmental variable %r " "is not a str (only str is allowed; got %r)" % (k, v)) - content.append("%s=%s" % (encode(k),encode(v))) + content.append("%s=%s" % (encode(k), encode(v))) if content: content = ";".join(content) content = self.signer.sign(content) cookie = '%s=%s; Path=/;' % (self.cookie_name, content) if 'https' == environ['wsgi.url_scheme']: cookie += ' secure;' - response_headers.append(('Set-Cookie',cookie)) + response_headers.append(('Set-Cookie', cookie)) return start_response(status, response_headers, exc_info) return self.application(environ, response_hook) diff --git a/paste/auth/digest.py b/paste/auth/digest.py index 0fe380b..ad5e4a3 100644 --- a/paste/auth/digest.py +++ b/paste/auth/digest.py @@ -35,7 +35,7 @@ import md5, time, random def digest_password(realm, username, password): """ construct the appropriate hashcode needed for HTTP digest """ - return md5.md5("%s:%s:%s" % (username,realm,password)).hexdigest() + return md5.md5("%s:%s:%s" % (username, realm, password)).hexdigest() class AuthDigestAuthenticator: """ implementation of RFC 2617 - HTTP Digest Authentication """ @@ -46,14 +46,16 @@ class AuthDigestAuthenticator: def build_authentication(self, stale = ''): """ builds the authentication error """ - nonce = md5.md5("%s:%s" % (time.time(),random.random())).hexdigest() - opaque = md5.md5("%s:%s" % (time.time(),random.random())).hexdigest() + nonce = md5.md5( + "%s:%s" % (time.time(), random.random())).hexdigest() + opaque = md5.md5( + "%s:%s" % (time.time(), random.random())).hexdigest() self.nonce[nonce] = None - parts = { 'realm': self.realm, 'qop': 'auth', - 'nonce': nonce, 'opaque': opaque } + parts = {'realm': self.realm, 'qop': 'auth', + 'nonce': nonce, 'opaque': opaque } if stale: parts['stale'] = 'true' - head = ", ".join(['%s="%s"' % (k,v) for (k,v) in parts.items()]) + head = ", ".join(['%s="%s"' % (k, v) for (k, v) in parts.items()]) head = [("WWW-Authenticate", 'Digest %s' % head)] return HTTPUnauthorized(headers=head) @@ -62,11 +64,11 @@ class AuthDigestAuthenticator: """ computes the authentication, raises error if unsuccessful """ if not ha1: return self.build_authentication() - ha2 = md5.md5('%s:%s' % (method,path)).hexdigest() + ha2 = md5.md5('%s:%s' % (method, path)).hexdigest() if qop: - chk = "%s:%s:%s:%s:%s:%s" % (ha1,nonce,nc,cnonce,qop,ha2) + chk = "%s:%s:%s:%s:%s:%s" % (ha1, nonce, nc, cnonce, qop, ha2) else: - chk = "%s:%s:%s" % (ha1,nonce,ha2) + chk = "%s:%s:%s" % (ha1, nonce, ha2) if response != md5.md5(chk).hexdigest(): if nonce in self.nonce: del self.nonce[nonce] @@ -88,24 +90,24 @@ class AuthDigestAuthenticator: authorization = AUTHORIZATION(environ) if not authorization: return self.build_authentication() - (authmeth, auth) = authorization.split(" ",1) + (authmeth, auth) = authorization.split(" ", 1) if 'digest' != authmeth.lower(): return self.build_authentication() amap = {} for itm in auth.split(", "): - (k,v) = [s.strip() for s in itm.split("=",1)] - amap[k] = v.replace('"','') + (k,v) = [s.strip() for s in itm.split("=", 1)] + amap[k] = v.replace('"', '') try: username = amap['username'] authpath = amap['uri'] nonce = amap['nonce'] realm = amap['realm'] response = amap['response'] - assert authpath.split("?",1)[0] in fullpath + assert authpath.split("?", 1)[0] in fullpath assert realm == self.realm - qop = amap.get('qop','') - cnonce = amap.get('cnonce','') - nc = amap.get('nc','00000000') + qop = amap.get('qop', '') + cnonce = amap.get('cnonce', '') + nc = amap.get('nc', '00000000') if qop: assert 'auth' == qop assert nonce and nc diff --git a/paste/auth/form.py b/paste/auth/form.py index f13abf8..dd4a06e 100644 --- a/paste/auth/form.py +++ b/paste/auth/form.py @@ -25,7 +25,7 @@ serving on... """ from paste.request import construct_url, parse_formvars -TEMPLATE ="""\ +TEMPLATE = """\ <html> <head><title>Please Login!</title></head> <body> @@ -113,8 +113,8 @@ class AuthFormHandler: return self.application(environ, start_response) content = self.template % construct_url(environ) - start_response("200 OK",(('Content-Type', 'text/html'), - ('Content-Length', len(content)))) + start_response("200 OK", (('Content-Type', 'text/html'), + ('Content-Length', len(content)))) return [content] middleware = AuthFormHandler diff --git a/paste/auth/multi.py b/paste/auth/multi.py index 12c9f26..e3516c2 100644 --- a/paste/auth/multi.py +++ b/paste/auth/multi.py @@ -54,7 +54,7 @@ class MultiHandler: def add_method(self, name, factory, *args, **kwargs): self.binding[name] = factory(self.application, *args, **kwargs) def add_predicate(self, name, checker): - self.predicate.append((checker,self.binding[name])) + self.predicate.append((checker, self.binding[name])) def set_default(self, name): """ set default authentication method """ self.default = self.binding[name] @@ -64,7 +64,7 @@ class MultiHandler: self.add_predicate(name, lambda environ: lookfor in environ.get('QUERY_STRING','')) def __call__(self, environ, start_response): - for (checker,binding) in self.predicate: + for (checker, binding) in self.predicate: if checker(environ): return binding(environ, start_response) return self.default(environ, start_response) diff --git a/paste/auth/open_id.py b/paste/auth/open_id.py index eb01150..077f049 100644 --- a/paste/auth/open_id.py +++ b/paste/auth/open_id.py @@ -153,7 +153,8 @@ class AuthOpenIDHandler(object): # @@: Do I need to append something to go back to where we # came from? was_401.append(1) - def dummy_writer(v): pass + def dummy_writer(v): + pass return dummy_writer else: return start_response(status, headers, exc_info) diff --git a/paste/cascade.py b/paste/cascade.py index 847e73c..9176320 100644 --- a/paste/cascade.py +++ b/paste/cascade.py @@ -5,8 +5,8 @@ Cascades through several applications, so long as applications return ``404 Not Found``. """ -import httpexceptions -from util import converters +from paste import httpexceptions +from paste.util import converters __all__ = ['Cascade'] diff --git a/paste/cgiapp.py b/paste/cgiapp.py index 17c308d..67f2654 100644 --- a/paste/cgiapp.py +++ b/paste/cgiapp.py @@ -10,7 +10,6 @@ try: import select except ImportError: select = None -import warnings from paste.util import converters @@ -48,7 +47,7 @@ class CGIApplication(object): if '?' in script: assert query_string is None, ( "You cannot have '?' in your script name (%r) and also " - "give a query_string (%r)" % (self.script, query_string)) + "give a query_string (%r)" % (script, query_string)) script, query_string = script.split('?', 1) if os.path.abspath(script) != script: # relative path diff --git a/paste/cgitb_catcher.py b/paste/cgitb_catcher.py index 09d7b49..6278103 100644 --- a/paste/cgitb_catcher.py +++ b/paste/cgitb_catcher.py @@ -83,7 +83,7 @@ class CgitbMiddleware(object): hook(*exc_info) return dummy_file.getvalue() -def make_cgitb_middleware(self, app, global_conf, +def make_cgitb_middleware(app, global_conf, display=NoDefault, logdir=None, context=5, diff --git a/paste/debug/debugapp.py b/paste/debug/debugapp.py index 0e4e82f..caabd03 100755 --- a/paste/debug/debugapp.py +++ b/paste/debug/debugapp.py @@ -60,8 +60,8 @@ class SlowConsumer: '<input type="submit" >\n' '</form></body></html>\n') print "bingles" - start_response("200 OK",[('Content-Type', 'text/html'), - ('Content-Length', len(body))]) + start_response("200 OK", [('Content-Type', 'text/html'), + ('Content-Length', len(body))]) return [body] def make_test_app(global_conf): diff --git a/paste/debug/doctest_webapp.py b/paste/debug/doctest_webapp.py index a0ca130..935b291 100755 --- a/paste/debug/doctest_webapp.py +++ b/paste/debug/doctest_webapp.py @@ -167,7 +167,6 @@ def show(path_info, example_name): print result def html_matches(pattern, text): - return True regex = re.escape(pattern) regex = regex.replace(r'\.\.\.', '.*') regex = re.sub(r'0x[0-9a-f]+', '.*', regex) @@ -402,10 +401,11 @@ class LongFormDocTestParser(doctest.DocTestParser): # Create an Example, and add it to the list. if not self._IS_BLANK_OR_COMMENT(source): # @@: Erg, this is the only line I need to change... - output.append( doctest.Example(source, want, exc_msg, - lineno=lineno, - indent=min_indent+len(m.group('indent') or m.group('runindent')), - options=options) ) + output.append(doctest.Example( + source, want, exc_msg, + lineno=lineno, + indent=min_indent+len(m.group('indent') or m.group('runindent')), + options=options)) # Update lineno (lines inside this example) lineno += string.count('\n', m.start(), m.end()) # Update charno. diff --git a/paste/debug/testserver.py b/paste/debug/testserver.py index 3bc2bd9..26c477a 100755 --- a/paste/debug/testserver.py +++ b/paste/debug/testserver.py @@ -61,7 +61,7 @@ class WSGIRegressionServer(WSGIServer): [self.pending.append(True) for x in range(count)] def serve(application, host=None, port=None, handler=None): - server = WSGIRegressionServer(application,host,port,handler) + server = WSGIRegressionServer(application, host, port, handler) print "serving on %s:%s" % server.server_address server.serve_forever() return server diff --git a/paste/errordocument.py b/paste/errordocument.py index faa6425..59277f5 100644 --- a/paste/errordocument.py +++ b/paste/errordocument.py @@ -10,9 +10,7 @@ URL where the content can be displayed to the user as an error document. """ import warnings -from urllib import urlencode from urlparse import urlparse -from paste.wsgilib import chained_app_iters from paste.recursive import ForwardRequestException, RecursiveMiddleware from paste.util import converters @@ -154,7 +152,7 @@ class StatusBasedForward: status_code = status.split(' ') try: code = int(status_code[0]) - except ValueError, TypeError: + except (ValueError, TypeError): raise Exception( 'StatusBasedForward middleware ' 'received an invalid status code %s'%repr(status_code[0]) @@ -313,21 +311,22 @@ class _StatusBasedRedirect: try: code, message = code_message[0] except: - code, message = ['',''] + code, message = ['', ''] environ['wsgi.errors'].write( 'Error occurred in _StatusBasedRedirect ' 'intercepting the response: '+str(error) ) - return [self.fallback_template%{'message':message,'code':code}] + return [self.fallback_template + % {'message': message, 'code': code}] else: if url: - url_= url[0] + url_ = url[0] new_environ = {} for k, v in environ.items(): if k != 'QUERY_STRING': new_environ['QUERY_STRING'] = urlparse(url_)[4] else: - new_environ[k]=v + new_environ[k] = v class InvalidForward(Exception): pass def eat_start_response(status, headers, exc_info=None): @@ -339,7 +338,7 @@ class _StatusBasedRedirect: raise InvalidForward( "The URL %s to internally forward " "to in order to create an error document did not " - "return a '200' status code."%url_ + "return a '200' status code." % url_ ) forward = environ['paste.recursive.forward'] old_start_response = forward.start_response diff --git a/paste/evalexception/__init__.py b/paste/evalexception/__init__.py index 298d72b..a19cf85 100644 --- a/paste/evalexception/__init__.py +++ b/paste/evalexception/__init__.py @@ -3,5 +3,5 @@ """ An exception handler for interactive debugging """ -from middleware import EvalException +from paste.evalexception.middleware import EvalException diff --git a/paste/exceptions/collector.py b/paste/exceptions/collector.py index 93eee4c..c6d00e3 100644 --- a/paste/exceptions/collector.py +++ b/paste/exceptions/collector.py @@ -28,7 +28,7 @@ try: except ImportError: from StringIO import StringIO import linecache -import serial_number_generator +from paste.exceptions import serial_number_generator DEBUG_EXCEPTION_FORMATTER = True DEBUG_IDENT_PREFIX = 'E-' diff --git a/paste/exceptions/reporter.py b/paste/exceptions/reporter.py index c09a7a6..3ebebbf 100644 --- a/paste/exceptions/reporter.py +++ b/paste/exceptions/reporter.py @@ -5,7 +5,7 @@ from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart import smtplib import time -import formatter +from paste.exceptions import formatter class Reporter: diff --git a/paste/fileapp.py b/paste/fileapp.py index 62dbe1a..0d59d06 100644 --- a/paste/fileapp.py +++ b/paste/fileapp.py @@ -10,13 +10,13 @@ if-modified-since request header. """ import os, time, mimetypes -from httpexceptions import * -from httpheaders import * +from paste.httpexceptions import * +from paste.httpheaders import * CACHE_SIZE = 4096 BLOCK_SIZE = 4096 * 16 -__all__ = ['DataApp','FileApp'] +__all__ = ['DataApp', 'FileApp'] class DataApp(object): """ @@ -54,16 +54,16 @@ class DataApp(object): """ def __init__(self, content, headers=None, **kwargs): - assert isinstance(headers,(type(None),list)) + assert isinstance(headers, (type(None), list)) self.expires = None self.content = None self.content_length = None self.last_modified = 0 self.headers = headers or [] - for (k,v) in kwargs.items(): + for (k, v) in kwargs.items(): header = get_header(k) - header.update(self.headers,v) - ACCEPT_RANGES.update(self.headers,bytes=True) + header.update(self.headers, v) + ACCEPT_RANGES.update(self.headers, bytes=True) if not CONTENT_TYPE(self.headers): CONTENT_TYPE.update(self.headers) if content is not None: @@ -98,7 +98,7 @@ class DataApp(object): # horribly inefficient, n^2 performance, yuck! for head in list_headers(entity=True): head.delete(headers) - start_response('304 Not Modified',headers) + start_response('304 Not Modified', headers) return [''] # empty body except HTTPBadRequest, exce: return exce.wsgi_application(environ, start_response) @@ -116,10 +116,10 @@ class DataApp(object): except HTTPBadRequest, exce: return exce.wsgi_application(environ, start_response) - (lower,upper) = (0, self.content_length - 1) + (lower, upper) = (0, self.content_length - 1) range = RANGE.parse(environ) if range and 'bytes' == range[0] and 1 == len(range[1]): - (lower,upper) = range[1][0] + (lower, upper) = range[1][0] upper = upper or (self.content_length - 1) if upper >= self.content_length or lower > upper: return HTTPRequestRangeNotSatisfiable(( @@ -186,7 +186,7 @@ class FileApp(DataApp): return exc.wsgi_application( environ, start_response) retval = DataApp.__call__(self, environ, start_response) - if isinstance(retval,list): + if isinstance(retval, list): # cached content, exception, or not-modified return retval (lower, content_length) = retval diff --git a/paste/fixture.py b/paste/fixture.py index e5c7ef0..5a49f41 100644 --- a/paste/fixture.py +++ b/paste/fixture.py @@ -57,6 +57,10 @@ class Dummy_smtplib(object): existing = None def __init__(self, server): + import warnings + warnings.warn( + 'Dummy_smtplib is not maintained and is deprecated', + DeprecationWarning, 2) assert not self.existing, ( "smtplib.SMTP() called again before Dummy_smtplib.existing.reset() " "called.") diff --git a/paste/flup_session.py b/paste/flup_session.py index cd1e467..43a34bc 100644 --- a/paste/flup_session.py +++ b/paste/flup_session.py @@ -16,8 +16,8 @@ cookies, and there's no way to delete a session except to clear its data. """ -import httpexceptions -import wsgilib +from paste import httpexceptions +from paste import wsgilib import flup.middleware.session flup_session = flup.middleware.session diff --git a/paste/modpython.py b/paste/modpython.py index d2b7a7f..189e29a 100644 --- a/paste/modpython.py +++ b/paste/modpython.py @@ -143,7 +143,7 @@ class Handler: env['wsgi.input'] = InputWrapper(req) env['wsgi.errors'] = ErrorWrapper(req) - env['wsgi.version'] = (1,0) + env['wsgi.version'] = (1, 0) env['wsgi.run_once'] = False if env.get("HTTPS") in ('yes', 'on', '1'): env['wsgi.url_scheme'] = 'https' diff --git a/paste/progress.py b/paste/progress.py index ca51d18..91f245c 100755 --- a/paste/progress.py +++ b/paste/progress.py @@ -32,7 +32,7 @@ serving on... This is experimental, and will change in the future. """ import time -from wsgilib import catch_errors +from paste.wsgilib import catch_errors DEFAULT_THRESHOLD = 1024 * 1024 # one megabyte DEFAULT_TIMEOUT = 60*5 # five minutes @@ -58,7 +58,6 @@ class _ProgressFile(object): riter = iter(self._ProgressFile_rfile) def iterwrap(): for chunk in riter: - size = len(chunk) environ[ENVIRON_RECEIVED] += len(chunk) yield chunk return iter(iterwrap) @@ -183,8 +182,8 @@ class UploadProgressReporter: self.monitor = monitor def match(self, search_environ, upload_environ): - if search_environ.get('REMOTE_USER',None) == \ - upload_environ.get('REMOTE_USER',0): + if search_environ.get('REMOTE_USER', None) == \ + upload_environ.get('REMOTE_USER', 0): return True return False @@ -207,16 +206,16 @@ class UploadProgressReporter: for map in [self.report(env) for env in self.monitor.uploads() if self.match(environ, env)]: parts = [] - for k,v in map.items(): - v = str(v).replace("\\","\\\\").replace('"','\\"') - parts.append('%s: "%s"' % (k,v)) + for k, v in map.items(): + v = str(v).replace("\\", "\\\\").replace('"', '\\"') + parts.append('%s: "%s"' % (k, v)) body.append("{ %s }" % ", ".join(parts)) body = "[ %s ]" % ", ".join(body) - start_response("200 OK", [ ('Content-Type', 'text/plain'), - ('Content-Length', len(body))]) + start_response("200 OK", [('Content-Type', 'text/plain'), + ('Content-Length', len(body))]) return [body] -__all__ = ['UploadProgressMonitor','UploadProgressReporter'] +__all__ = ['UploadProgressMonitor', 'UploadProgressReporter'] if "__main__" == __name__: import doctest diff --git a/paste/recursive.py b/paste/recursive.py index a56c174..81661c6 100644 --- a/paste/recursive.py +++ b/paste/recursive.py @@ -24,7 +24,6 @@ Raise ``ForwardRequestException(new_path_info)`` to do a forward """ from cStringIO import StringIO -from urlparse import urlparse import warnings __all__ = ['RecursiveMiddleware'] @@ -43,7 +42,8 @@ class CheckForRecursionMiddleware: "Forwarding loop detected; %r visited twice (internal " "redirect path: %s)" % (path_info, self.env['paste.recursive.old_path_info'])) - self.env.setdefault('paste.recursive.old_path_info', []).append(self.env.get('PATH_INFO', '')) + old_path_info = self.env.setdefault('paste.recursive.old_path_info', []) + old_path_info.append(self.env.get('PATH_INFO', '')) return self.app(environ, start_response) class RecursiveMiddleware(object): @@ -75,12 +75,13 @@ class RecursiveMiddleware(object): environ, start_response) my_script_name = environ.get('SCRIPT_NAME', '') - current_path_info = environ.get('PATH_INFO', '') environ['paste.recursive.script_name'] = my_script_name try: return self.application(environ, start_response) except ForwardRequestException, e: - return CheckForRecursionMiddleware(e.factory(self), environ)(environ, start_response) + middleware = CheckForRecursionMiddleware( + e.factory(self), environ) + return middleware(environ, start_response) class ForwardRequestException(Exception): """ @@ -169,15 +170,20 @@ class ForwardRequestException(Exception): url=None, environ={}, factory=None, - path_info=None, - ): + path_info=None): # Check no incompatible options have been chosen if factory and url: - raise TypeError('You cannot specify factory and a url in ForwardRequestException') + raise TypeError( + 'You cannot specify factory and a url in ' + 'ForwardRequestException') elif factory and environ: - raise TypeError('You cannot specify factory and environ in ForwardRequestException') + raise TypeError( + 'You cannot specify factory and environ in ' + 'ForwardRequestException') if url and environ: - raise TypeError('You cannot specify environ and url in ForwardRequestException') + raise TypeError( + 'You cannot specify environ and url in ' + 'ForwardRequestException') # set the path_info or warn about its use. if path_info: @@ -258,6 +264,9 @@ class Recursive(object): environ['REQUEST_METHOD'] = 'GET' return self.activate(environ) + def activate(self, environ): + raise NotImplementedError + def __repr__(self): return '<%s.%s from %s>' % ( self.__class__.__module__, diff --git a/paste/registry.py b/paste/registry.py index 283fd39..446c009 100644 --- a/paste/registry.py +++ b/paste/registry.py @@ -92,7 +92,6 @@ quick way to work around it is documented. """ import warnings import paste.util.threadinglocal as threadinglocal -from paste import wsgilib __all__ = ['StackedObjectProxy', 'RegistryManager'] diff --git a/paste/request.py b/paste/request.py index dc3f20a..405011b 100644 --- a/paste/request.py +++ b/paste/request.py @@ -18,11 +18,13 @@ environment to solve common requirements. """ import cgi -import textwrap from Cookie import SimpleCookie from StringIO import StringIO import urlparse -from util.UserDict24 import DictMixin, IterableUserDict, UserDict +try: + from UserDict import DictMixin +except ImportError: + from paste.util.UserDict24 import DictMixin from paste.util.multidict import MultiDict __all__ = ['get_cookies', 'get_cookie_dict', 'parse_querystring', diff --git a/paste/response.py b/paste/response.py index fd4acf5..7d3c72d 100644 --- a/paste/response.py +++ b/paste/response.py @@ -154,10 +154,10 @@ def replace_header(headers, name, value): if headers[i][0].lower() == name: assert not result, "two values for the header '%s' found" % name result = headers[i][1] - headers[i] = (name,value) + headers[i] = (name, value) i += 1 if not result: - headers.append((name,value)) + headers.append((name, value)) return result diff --git a/paste/session.py b/paste/session.py index 387cf3f..cd2c324 100644 --- a/paste/session.py +++ b/paste/session.py @@ -35,8 +35,8 @@ try: import cPickle except ImportError: import pickle as cPickle -import wsgilib -import request +from paste import wsgilib +from paste import request class SessionMiddleware(object): diff --git a/paste/transaction.py b/paste/transaction.py index 94910a5..77e25b8 100644 --- a/paste/transaction.py +++ b/paste/transaction.py @@ -25,9 +25,9 @@ class TransactionManagerMiddleware(object): environ['paste.transaction_manager'] = manager = Manager() # This makes sure nothing else traps unexpected exceptions: environ['paste.throw_errors'] = True - return wsgilib.catch_errors(application, environ, start_response, - error_callback=manager.error, - ok_callback=manager.finish) + return catch_errors(self.application, environ, start_response, + error_callback=manager.error, + ok_callback=manager.finish) class Manager(object): @@ -69,7 +69,7 @@ class ConnectionFactory(object): self.quote = self.module.PgQuoteString def __call__(self, environ=None): - conn = self.module.connect(*self.args,**self.kwargs) + conn = self.module.connect(*self.args, **self.kwargs) conn.__dict__['module'] = self.module conn.__dict__['quote'] = self.quote return conn @@ -103,14 +103,14 @@ def BasicTransactionHandler(application, factory): finalizer, finalizer) return basic_transaction -__all__ = ['ConnectionFactory','BasicTransactionHandler'] +__all__ = ['ConnectionFactory', 'BasicTransactionHandler'] if '__main__' == __name__ and False: from pyPgSQL import PgSQL - factory = ConnectionFactory(PgSQL,database="testing") + factory = ConnectionFactory(PgSQL, database="testing") conn = factory() curr = conn.cursor() curr.execute("SELECT now(), %s" % conn.quote("B'n\\'gles")) - (time,bing) = curr.fetchone() + (time, bing) = curr.fetchone() print bing, time diff --git a/paste/urlmap.py b/paste/urlmap.py index 70a552a..bb39e49 100644 --- a/paste/urlmap.py +++ b/paste/urlmap.py @@ -7,7 +7,7 @@ Map URL prefixes to WSGI applications. See ``URLMap`` from UserDict import DictMixin import re import os -import httpexceptions +from paste import httpexceptions __all__ = ['URLMap', 'PathProxyURLMap'] diff --git a/paste/urlparser.py b/paste/urlparser.py index 367fa02..6aa5105 100644 --- a/paste/urlparser.py +++ b/paste/urlparser.py @@ -10,10 +10,10 @@ import imp import urllib import pkg_resources import mimetypes -import request -import fileapp +from paste import request +from paste import fileapp from paste.util import import_string -import httpexceptions +from paste import httpexceptions from httpheaders import ETAG from paste.util import converters @@ -468,7 +468,7 @@ class StaticURLParser(object): if str(mytime) == if_none_match: headers = [] ETAG.update(headers, mytime) - start_response('304 Not Modified',headers) + start_response('304 Not Modified', headers) return [''] # empty body fa = fileapp.FileApp(full) diff --git a/paste/util/datetimeutil.py b/paste/util/datetimeutil.py index 6df3993..b1a7f38 100644 --- a/paste/util/datetimeutil.py +++ b/paste/util/datetimeutil.py @@ -53,7 +53,7 @@ correctly. ``timedelta`` values will have a normalized representation.
"""
-from datetime import timedelta, time, date, datetime
+from datetime import timedelta, time, date
from time import localtime
import string
@@ -84,14 +84,16 @@ def parse_timedelta(val): fMin = ("m" in val or ":" in val)
fFraction = "." in val
for noise in "minu:teshour()":
- val = string.replace(val,noise,' ')
+ val = string.replace(val, noise, ' ')
val = string.strip(val)
val = string.split(val)
hr = 0.0
mi = 0
val.reverse()
- if fHour: hr = int(val.pop())
- if fMin: mi = int(val.pop())
+ if fHour:
+ hr = int(val.pop())
+ if fMin:
+ mi = int(val.pop())
if len(val) > 0 and not hr:
hr = int(val.pop())
return timedelta(hours=hr, minutes=mi)
@@ -110,7 +112,7 @@ def normalize_timedelta(val): return ''
hr = val.seconds/3600
mn = (val.seconds % 3600)/60
- return "%d.%02d" % (hr,mn*100/60)
+ return "%d.%02d" % (hr, mn * 100/60)
#
# time
@@ -120,10 +122,10 @@ def parse_time(val): return None
hr = mi = 0
val = string.lower(val)
- amflag = (-1 != string.find(val,'a')) # set if AM is found
- pmflag = (-1 != string.find(val,'p')) # set if PM is found
+ amflag = (-1 != string.find(val, 'a')) # set if AM is found
+ pmflag = (-1 != string.find(val, 'p')) # set if PM is found
for noise in ":amp.":
- val = string.replace(val,noise,' ')
+ val = string.replace(val, noise, ' ')
val = string.split(val)
if len(val) > 1:
hr = int(val[0])
@@ -147,9 +149,11 @@ def parse_time(val): mi = int(val[-2:])
else:
hr = int(val[:1])
- if amflag and hr >= 12: hr = hr - 12
- if pmflag and hr < 12 : hr = hr + 12
- return time(hr,mi)
+ if amflag and hr >= 12:
+ hr = hr - 12
+ if pmflag and hr < 12:
+ hr = hr + 12
+ return time(hr, mi)
def normalize_time(value, ampm):
if not value:
@@ -166,7 +170,7 @@ def normalize_time(value, ampm): am = "PM"
if hr > 12:
hr = hr - 12
- return "%02d:%02d %s" % (hr,value.minute,am)
+ return "%02d:%02d %s" % (hr, value.minute, am)
#
# Date Processing
@@ -178,16 +182,18 @@ _str2num = {'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12 }
def _month(val):
- for (key,mon) in _str2num.items():
+ for (key, mon) in _str2num.items():
if key in val:
return mon
raise TypeError("unknown month '%s'" % val)
-_days_in_month = {1:31,2:28,3:31,4:30,5:31,6:30,
- 7:31,8:31,9:30,10:31,11:30,12:31 }
-_num2str = { 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun',
- 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec' }
-_wkdy = ("mon","tue","wed","thu","fri","sat","sun" )
+_days_in_month = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
+ 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31,
+ }
+_num2str = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
+ 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec',
+ }
+_wkdy = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
def parse_date(val):
if not(val):
@@ -198,13 +204,13 @@ def parse_date(val): # optimized check for YYYY-MM-DD
strict = val.split("-")
if len(strict) == 3:
- (y,m,d) = strict
+ (y, m, d) = strict
if "+" in d:
d = d.split("+")[0]
if " " in d:
d = d.split(" ")[0]
try:
- now = date(int(y),int(m),int(d))
+ now = date(int(y), int(m), int(d))
val = "xxx" + val[10:]
except ValueError:
pass
@@ -236,10 +242,10 @@ def parse_date(val): # ok, standard parsing
yr = mo = dy = None
- for noise in ('/','-',',','*'):
- val = string.replace(val,noise,' ')
+ for noise in ('/', '-', ',', '*'):
+ val = string.replace(val, noise, ' ')
for noise in _wkdy:
- val = string.replace(val,noise,' ')
+ val = string.replace(val, noise, ' ')
out = []
last = False
ldig = False
@@ -337,10 +343,13 @@ def parse_date(val): else:
raise TypeError("four digit year required")
tm = localtime()
- if mo is None: mo = tm[1]
- if dy is None: dy = tm[2]
- if yr is None: yr = tm[0]
- return date(yr,mo,dy)
+ if mo is None:
+ mo = tm[1]
+ if dy is None:
+ dy = tm[2]
+ if yr is None:
+ yr = tm[0]
+ return date(yr, mo, dy)
def normalize_date(val, iso8601=True):
if not val:
@@ -349,4 +358,4 @@ def normalize_date(val, iso8601=True): val = parse_date(val)
if iso8601:
return "%4d-%02d-%02d" % (val.year, val.month, val.day)
- return "%02d %s %4d" % (val.day,_num2str[val.month],val.year)
+ return "%02d %s %4d" % (val.day, _num2str[val.month], val.year)
diff --git a/paste/util/scgiserver.py b/paste/util/scgiserver.py index 332f6f1..b52ed9d 100644 --- a/paste/util/scgiserver.py +++ b/paste/util/scgiserver.py @@ -59,10 +59,10 @@ class SWAP(scgi_server.SCGIHandler): environ = self.read_env(input) environ['wsgi.input'] = input environ['wsgi.errors'] = sys.stderr - environ['wsgi.version'] = (1,0) + environ['wsgi.version'] = (1, 0) environ['wsgi.multithread'] = False environ['wsgi.multiprocess'] = True - environ['wsgi.run_once'] = False + environ['wsgi.run_once'] = False # dunno how SCGI does HTTPS signalling; can't test it myself... @CTB if environ.get('HTTPS','off') in ('on','1'): @@ -86,7 +86,7 @@ class SWAP(scgi_server.SCGIHandler): def write(data): chunks.append(data) - def start_response(status,response_headers,exc_info=None): + def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: @@ -97,7 +97,7 @@ class SWAP(scgi_server.SCGIHandler): elif headers_set: raise AssertionError("Headers already set!") - headers_set[:] = [status,response_headers] + headers_set[:] = [status, response_headers] return write ### diff --git a/paste/util/threadedprint.py b/paste/util/threadedprint.py index ed678fb..0cdcdd6 100644 --- a/paste/util/threadedprint.py +++ b/paste/util/threadedprint.py @@ -62,7 +62,7 @@ TODO import threading import sys -import filemixin +from paste.util import filemixin class PrintCatcher(filemixin.FileMixin): diff --git a/paste/util/threadinglocal.py b/paste/util/threadinglocal.py index 57afa17..06f2643 100644 --- a/paste/util/threadinglocal.py +++ b/paste/util/threadinglocal.py @@ -1,5 +1,9 @@ # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php +""" +Implementation of thread-local storage, for Python versions that don't +have thread local storage natively. +""" try: import threading diff --git a/paste/wsgilib.py b/paste/wsgilib.py index 9b3093f..4de2bc4 100644 --- a/paste/wsgilib.py +++ b/paste/wsgilib.py @@ -7,19 +7,14 @@ A module of many disparate routines. # functions which moved to paste.request and paste.response # Deprecated around 15 Dec 2005 -from request import get_cookies, parse_querystring, parse_formvars -from request import construct_url, path_info_split, path_info_pop -from response import HeaderDict, has_header, header_value, remove_header -from response import error_body_response, error_response, error_response_app +from paste.request import get_cookies, parse_querystring, parse_formvars +from paste.request import construct_url, path_info_split, path_info_pop +from paste.response import HeaderDict, has_header, header_value, remove_header +from paste.response import error_body_response, error_response, error_response_app from traceback import print_exception -from Cookie import SimpleCookie from cStringIO import StringIO -import mimetypes -import os -import cgi import sys -import re from urlparse import urlsplit import warnings @@ -180,7 +175,6 @@ def catch_errors(application, environ, start_response, error_callback, exc_info as its sole argument. If no errors occur and ok_callback is given, then it will be called with no arguments. """ - error_occurred = False try: app_iter = application(environ, start_response) except: @@ -227,7 +221,6 @@ def catch_errors_app(application, environ, start_response, error_callback_app, ``start_response`` (*with* the exc_info argument!) and return an iterator. """ - error_occurred = False try: app_iter = application(environ, start_response) except catch: @@ -309,7 +302,7 @@ def raw_interactive(application, path='', raise_on_wsgi_error=False, 'wsgi.run_once': False, } if path: - (_,_,path_info,query,fragment) = urlsplit(str(path)) + (_, _, path_info, query, fragment) = urlsplit(str(path)) basic_environ['PATH_INFO'] = path_info if query: basic_environ['QUERY_STRING'] = query @@ -404,7 +397,7 @@ def interactive(*args, **kw): return full.getvalue() interactive.proxy = 'raw_interactive' -def dump_environ(environ,start_response): +def dump_environ(environ, start_response): """ Application which simply dumps the current environment variables out as a plain text response. @@ -414,23 +407,23 @@ def dump_environ(environ,start_response): keys.sort() for k in keys: v = str(environ[k]).replace("\n","\n ") - output.append("%s: %s\n" % (k,v)) + output.append("%s: %s\n" % (k, v)) output.append("\n") - content_length = environ.get("CONTENT_LENGTH",'') + content_length = environ.get("CONTENT_LENGTH", '') if content_length: output.append(environ['wsgi.input'].read(int(content_length))) output.append("\n") output = "".join(output) headers = [('Content-Type', 'text/plain'), ('Content-Length', len(output))] - start_response("200 OK",headers) + start_response("200 OK", headers) return [output] def send_file(filename): warnings.warn( "wsgilib.send_file has been moved to paste.fileapp.FileApp", DeprecationWarning, 2) - import fileapp + from paste import fileapp return fileapp.FileApp(filename) def capture_output(environ, start_response, application): diff --git a/paste/wsgiwrappers.py b/paste/wsgiwrappers.py index c67431a..de5bf1d 100644 --- a/paste/wsgiwrappers.py +++ b/paste/wsgiwrappers.py @@ -54,7 +54,7 @@ class WSGIRequest(object): You are free to subclass this object. """ - def __init__(self, environ, urlvars={}): + def __init__(self, environ): self.environ = environ # This isn't "state" really, since the object is derivative: self.headers = EnvironHeaders(environ) @@ -140,8 +140,8 @@ class WSGIResponse(object): self.cookies = SimpleCookie() self.status_code = code if not mimetype: - mimetype = "%s; charset=%s" % (settings['content_type'], - settings['charset']) + mimetype = "%s; charset=%s" % (settings['content_type'], + settings['charset']) self.headers['Content-Type'] = mimetype if 'encoding_errors' in settings: @@ -218,10 +218,11 @@ class WSGIResponse(object): Define a cookie to be sent via the outgoing HTTP headers """ self.cookies[key] = value - for var in ('max_age', 'path', 'domain', 'secure', 'expires'): - val = locals()[var] - if val is not None: - self.cookies[key][var.replace('_', '-')] = val + for var_name, var_value in [ + ('max_age', max_age), ('path', path), ('domain', domain), + ('secure', secure), ('expires', expires)]: + if var_value is not None: + self.cookies[key][var_name.replace('_', '-')] = var_value def delete_cookie(self, key, path='/', domain=None): """ |
