Permalink
Browse files

cleaned some code

  • Loading branch information...
1 parent 20cb5a1 commit 0d3045bb410203ca99d186b9b13eb717a9c17d66 @collinanderson collinanderson committed Sep 11, 2014
@@ -16,7 +16,7 @@ def app(environ, start_response):
data = 'Hello, %s!\n' % arg
status = '200 OK'
response_headers = [
- ('Content-type','text/plain'),
+ ('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
View
@@ -24,11 +24,10 @@ def app(environ, start_response):
else:
data = environ['wsgi.input'].read()
-
status = '200 OK'
response_headers = [
- ('Content-type','text/plain'),
+ ('Content-type', 'text/plain'),
('Content-Length', str(len(data))),
('X-Gunicorn-Version', __version__),
("Test", "test тест"),
@@ -32,7 +32,6 @@ def home(request):
else:
form = MsgForm()
-
return render_to_response('home.html', {
'form': form,
'subject': subject,
@@ -18,5 +18,5 @@ def process_request(self, request):
self.queue.put(('REQUEST',))
def process_response(self, request, response):
- self.queue.put(('RESPONSE',response.status_code))
+ self.queue.put(('RESPONSE', response.status_code))
return response
@@ -30,7 +30,6 @@ def home(request):
message = form.cleaned_data['message']
f = request.FILES['f']
-
if not hasattr(f, "fileno"):
size = len(f.read())
else:
@@ -41,7 +40,6 @@ def home(request):
else:
form = MsgForm()
-
return render_to_response('home.html', {
'form': form,
'subject': subject,
@@ -157,4 +157,4 @@
}
}
-SOME_VALUE="test on reload"
+SOME_VALUE = "test on reload"
@@ -20,7 +20,7 @@ def app(environ, start_response):
data = b'Hello, World!\n'
status = '200 OK'
response_headers = [
- ('Content-type','text/plain'),
+ ('Content-type', 'text/plain'),
('Transfer-Encoding', "chunked"),
]
sys.stdout.write('request received')
@@ -13,7 +13,7 @@ def __init__(self, mapping):
def __call__(self, environ, start_response):
host = environ.get("HTTP_HOST", "")
- host = host.split(":")[0] # strip port
+ host = host.split(":")[0] # strip port
for pattern, app in self.mapping:
if re.match("^" + pattern + "$", host):
@@ -16,7 +16,7 @@ def app(environ, start_response):
f = open(fname, 'rb')
response_headers = [
- ('Content-type','text/plain'),
+ ('Content-type', 'text/plain'),
]
start_response(status, response_headers)
@@ -12,8 +12,9 @@ def app(environ, start_response):
data = b'Hello, World!\n'
status = '200 OK'
response_headers = [
- ('Content-type','text/plain'),
- ('Content-Length', str(len(data))) ]
+ ('Content-type', 'text/plain'),
+ ('Content-Length', str(len(data))),
+ ]
sys.stdout.write('request received, pausing 10 seconds')
sys.stdout.flush()
time.sleep(10)
View
@@ -22,7 +22,7 @@ def app(environ, start_response):
status = '200 OK'
response_headers = [
- ('Content-type','text/plain'),
+ ('Content-type', 'text/plain'),
('Content-Length', str(len(data))),
('X-Gunicorn-Version', __version__),
("Test", "test тест"),
View
@@ -13,8 +13,9 @@ def app(environ, start_response):
data = b'Hello, World!\n'
status = '200 OK'
response_headers = [
- ('Content-type','text/plain'),
- ('Content-Length', str(len(data))) ]
+ ('Content-type', 'text/plain'),
+ ('Content-Length', str(len(data))),
+ ]
sys.stdout.write('request will timeout')
sys.stdout.flush()
time.sleep(35)
@@ -22,7 +22,6 @@ def memory_usage(self, pid):
used_mem = sum(int(x) for x in out.split('\n')[1:])
return used_mem
-
def run(self):
while True:
for (pid, worker) in list(self.server.WORKERS.items()):
@@ -126,7 +126,7 @@ class PasterServerApplication(PasterBaseApplication):
def __init__(self, app, gcfg=None, host="127.0.0.1", port=None, *args, **kwargs):
self.cfg = Config()
- self.gcfg = gcfg # need to hold this for app_config
+ self.gcfg = gcfg # need to hold this for app_config
self.app = app
self.callable = None
View
@@ -43,7 +43,7 @@ class Arbiter(object):
# I love dynamic languages
SIG_QUEUE = []
- SIGNALS = [getattr(signal, "SIG%s" % x) \
+ SIGNALS = [getattr(signal, "SIG%s" % x)
for x in "HUP QUIT INT TERM TTIN TTOU USR1 USR2 WINCH".split()]
SIG_NAMES = dict(
(getattr(signal, name), name[3:].lower()) for name in dir(signal)
@@ -492,15 +492,15 @@ def manage_workers(self):
self.kill_worker(pid, signal.SIGTERM)
self.log.debug("{0} workers".format(len(workers)),
- extra={ "metric": "gunicorn.workers",
- "value": len(workers),
- "mtype": "gauge"})
+ extra={"metric": "gunicorn.workers",
+ "value": len(workers),
+ "mtype": "gauge"})
def spawn_worker(self):
self.worker_age += 1
worker = self.worker_class(self.worker_age, self.pid, self.LISTENERS,
- self.app, self.timeout / 2.0,
- self.cfg, self.log)
+ self.app, self.timeout / 2.0,
+ self.cfg, self.log)
self.cfg.pre_fork(self, worker)
pid = os.fork()
if pid != 0:
View
@@ -8,7 +8,7 @@
import inspect
try:
import argparse
-except ImportError: # python 2.6
+except ImportError: # python 2.6
from . import argparse_compat as argparse
import os
import pwd
@@ -73,7 +73,7 @@ def parser(self):
parser = argparse.ArgumentParser(**kwargs)
parser.add_argument("-v", "--version",
action="version", default=argparse.SUPPRESS,
- version="%(prog)s (version " + __version__ + ")\n",
+ version="%(prog)s (version " + __version__ + ")\n",
help="show program's version number and exit")
parser.add_argument("args", nargs="*", help=argparse.SUPPRESS)
@@ -224,8 +224,6 @@ class Setting(object):
nargs = None
const = None
-
-
def __init__(self):
if self.default is not None:
self.set(self.default)
@@ -432,7 +430,7 @@ def validate_file(val):
# valid if the value is a string
val = validate_string(val)
- # transform relative paths
+ # transform relative paths
path = os.path.abspath(os.path.normpath(os.path.join(util.getcwd(), val)))
# test if the path exists
@@ -1648,6 +1646,6 @@ class StatsdHost(Setting):
meta = "STATSD_ADDR"
default = None
validator = validate_hostport
- desc ="""\
+ desc = """\
host:port of the statsd server to log to
"""
@@ -202,8 +202,8 @@ def setup(self, cfg):
fileConfig(cfg.logconfig, defaults=CONFIG_DEFAULTS,
disable_existing_loggers=False)
else:
- raise RuntimeError("Error: log config '%s' not found" %
- cfg.logconfig)
+ msg = "Error: log config '%s' not found"
+ raise RuntimeError(msg % cfg.logconfig)
def critical(self, msg, *args, **kwargs):
self.error_log.critical(msg, *args, **kwargs)
@@ -16,10 +16,10 @@
raise ImportError
SUPPORTED_PLATFORMS = (
- 'darwin',
- 'freebsd',
- 'dragonfly',
- 'linux2')
+ 'darwin',
+ 'freebsd',
+ 'dragonfly',
+ 'linux2')
if sys.version_info < (2, 6) or \
sys.platform not in SUPPORTED_PLATFORMS:
@@ -101,7 +101,7 @@ def proxy_environ(req):
return {
"PROXY_PROTOCOL": info["proxy_protocol"],
"REMOTE_ADDR": info["client_addr"],
- "REMOTE_PORT": str(info["client_port"]),
+ "REMOTE_PORT": str(info["client_port"]),
"PROXY_ADDR": info["proxy_addr"],
"PROXY_PORT": str(info["proxy_port"]),
}
@@ -374,7 +374,7 @@ def sendfile_use_send(self, fileno, fo_offset, nbytes):
sent += len(data)
if sent > nbytes:
- data = data[:nbytes-sent]
+ data = data[:nbytes - sent]
util.write(self.sock, data, self.chunked)
@@ -82,14 +82,13 @@ def log(self, lvl, msg, *args, **kwargs):
except Exception:
pass
-
# access logging
def access(self, resp, req, environ, request_time):
"""Measure request duration
request_time is a datetime.timedelta
"""
Logger.access(self, resp, req, environ, request_time)
- duration_in_ms = request_time.seconds * 1000 + float(request_time.microseconds)/10**3
+ duration_in_ms = request_time.seconds * 1000 + float(request_time.microseconds) / 10 ** 3
self.histogram("gunicorn.request.duration", duration_in_ms)
self.increment("gunicorn.requests", 1)
self.increment("gunicorn.request.status.%d" % int(resp.status.split()[0]), 1)
View
@@ -24,8 +24,8 @@ def create(self, pid):
if oldpid:
if oldpid == os.getpid():
return
- raise RuntimeError("Already running on PID %s " \
- "(or pid file '%s' is stale)" % (oldpid, self.fname))
+ msg = "Already running on PID %s (or pid file '%s' is stale)"
+ raise RuntimeError(msg % (oldpid, self.fname))
self.pid = pid
View
@@ -70,8 +70,8 @@ def _resolve_name(name, package, level):
try:
dot = package.rindex('.', 0, dot)
except ValueError:
- raise ValueError("attempted relative import beyond top-level "
- "package")
+ msg = "attempted relative import beyond top-level package"
+ raise ValueError(msg)
return "%s.%s" % (package[:dot], name)
def import_module(name, package=None):
@@ -112,8 +112,8 @@ def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
return pkg_resources.load_entry_point(dist, section, name)
except:
exc = traceback.format_exc()
- raise RuntimeError("class uri %r invalid or not found: \n\n[%s]" % (uri,
- exc))
+ msg = "class uri %r invalid or not found: \n\n[%s]"
+ raise RuntimeError(msg % (uri, exc))
else:
components = uri.split('.')
if len(components) == 1:
@@ -130,18 +130,17 @@ def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
section, uri)
except:
exc = traceback.format_exc()
- raise RuntimeError("class uri %r invalid or not found: \n\n[%s]" % (uri,
- exc))
+ msg = "class uri %r invalid or not found: \n\n[%s]"
+ raise RuntimeError(msg % (uri, exc))
klass = components.pop(-1)
try:
mod = import_module('.'.join(components))
except:
exc = traceback.format_exc()
- raise RuntimeError(
- "class uri %r invalid or not found: \n\n[%s]" %
- (uri, exc))
+ msg = "class uri %r invalid or not found: \n\n[%s]"
+ raise RuntimeError(msg % (uri, exc))
return getattr(mod, klass)
@@ -215,7 +214,7 @@ def is_ipv6(addr):
socket.inet_pton(socket.AF_INET6, addr)
except socket.error: # not a valid address
return False
- except ValueError: # ipv6 not supported on this platform
+ except ValueError: # ipv6 not supported on this platform
return False
return True
@@ -230,7 +229,6 @@ def parse_address(netloc, default_port=8000):
if netloc.startswith("tcp://"):
netloc = netloc.split("tcp://")[1]
-
# get host
if '[' in netloc and ']' in netloc:
host = netloc.split(']')[0][1:].lower()
@@ -356,8 +354,8 @@ def import_app(module):
__import__(module)
except ImportError:
if module.endswith(".py") and os.path.exists(module):
- raise ImportError("Failed to find application, did "
- "you mean '%s:%s'?" % (module.rsplit(".", 1)[0], obj))
+ msg = "Failed to find application, did you mean '%s:%s'?"
+ raise ImportError(msg % (module.rsplit(".", 1)[0], obj))
else:
raise
@@ -6,13 +6,13 @@
import sys
# supported gunicorn workers.
-SUPPORTED_WORKERS={
- "sync": "gunicorn.workers.sync.SyncWorker",
- "eventlet": "gunicorn.workers.geventlet.EventletWorker",
- "gevent": "gunicorn.workers.ggevent.GeventWorker",
- "gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
- "gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
- "tornado": "gunicorn.workers.gtornado.TornadoWorker"}
+SUPPORTED_WORKERS = {
+ "sync": "gunicorn.workers.sync.SyncWorker",
+ "eventlet": "gunicorn.workers.geventlet.EventletWorker",
+ "gevent": "gunicorn.workers.ggevent.GeventWorker",
+ "gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
+ "gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
+ "tornado": "gunicorn.workers.gtornado.TornadoWorker"}
if sys.version_info >= (3, 3):
Oops, something went wrong.

0 comments on commit 0d3045b

Please sign in to comment.