mirror of
https://github.com/frappe/gunicorn.git
synced 2026-01-14 11:09:11 +08:00
cleaned some code
This commit is contained in:
parent
20cb5a1fbb
commit
0d3045bb41
@ -24,7 +24,6 @@ def app(environ, start_response):
|
|||||||
else:
|
else:
|
||||||
data = environ['wsgi.input'].read()
|
data = environ['wsgi.input'].read()
|
||||||
|
|
||||||
|
|
||||||
status = '200 OK'
|
status = '200 OK'
|
||||||
|
|
||||||
response_headers = [
|
response_headers = [
|
||||||
|
|||||||
@ -32,7 +32,6 @@ def home(request):
|
|||||||
else:
|
else:
|
||||||
form = MsgForm()
|
form = MsgForm()
|
||||||
|
|
||||||
|
|
||||||
return render_to_response('home.html', {
|
return render_to_response('home.html', {
|
||||||
'form': form,
|
'form': form,
|
||||||
'subject': subject,
|
'subject': subject,
|
||||||
|
|||||||
@ -30,7 +30,6 @@ def home(request):
|
|||||||
message = form.cleaned_data['message']
|
message = form.cleaned_data['message']
|
||||||
f = request.FILES['f']
|
f = request.FILES['f']
|
||||||
|
|
||||||
|
|
||||||
if not hasattr(f, "fileno"):
|
if not hasattr(f, "fileno"):
|
||||||
size = len(f.read())
|
size = len(f.read())
|
||||||
else:
|
else:
|
||||||
@ -41,7 +40,6 @@ def home(request):
|
|||||||
else:
|
else:
|
||||||
form = MsgForm()
|
form = MsgForm()
|
||||||
|
|
||||||
|
|
||||||
return render_to_response('home.html', {
|
return render_to_response('home.html', {
|
||||||
'form': form,
|
'form': form,
|
||||||
'subject': subject,
|
'subject': subject,
|
||||||
|
|||||||
@ -13,7 +13,8 @@ def app(environ, start_response):
|
|||||||
status = '200 OK'
|
status = '200 OK'
|
||||||
response_headers = [
|
response_headers = [
|
||||||
('Content-type', 'text/plain'),
|
('Content-type', 'text/plain'),
|
||||||
('Content-Length', str(len(data))) ]
|
('Content-Length', str(len(data))),
|
||||||
|
]
|
||||||
sys.stdout.write('request received, pausing 10 seconds')
|
sys.stdout.write('request received, pausing 10 seconds')
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
|
|||||||
@ -14,7 +14,8 @@ def app(environ, start_response):
|
|||||||
status = '200 OK'
|
status = '200 OK'
|
||||||
response_headers = [
|
response_headers = [
|
||||||
('Content-type', 'text/plain'),
|
('Content-type', 'text/plain'),
|
||||||
('Content-Length', str(len(data))) ]
|
('Content-Length', str(len(data))),
|
||||||
|
]
|
||||||
sys.stdout.write('request will timeout')
|
sys.stdout.write('request will timeout')
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
time.sleep(35)
|
time.sleep(35)
|
||||||
|
|||||||
@ -22,7 +22,6 @@ class MemoryWatch(threading.Thread):
|
|||||||
used_mem = sum(int(x) for x in out.split('\n')[1:])
|
used_mem = sum(int(x) for x in out.split('\n')[1:])
|
||||||
return used_mem
|
return used_mem
|
||||||
|
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
while True:
|
while True:
|
||||||
for (pid, worker) in list(self.server.WORKERS.items()):
|
for (pid, worker) in list(self.server.WORKERS.items()):
|
||||||
|
|||||||
@ -43,7 +43,7 @@ class Arbiter(object):
|
|||||||
|
|
||||||
# I love dynamic languages
|
# I love dynamic languages
|
||||||
SIG_QUEUE = []
|
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()]
|
for x in "HUP QUIT INT TERM TTIN TTOU USR1 USR2 WINCH".split()]
|
||||||
SIG_NAMES = dict(
|
SIG_NAMES = dict(
|
||||||
(getattr(signal, name), name[3:].lower()) for name in dir(signal)
|
(getattr(signal, name), name[3:].lower()) for name in dir(signal)
|
||||||
|
|||||||
@ -224,8 +224,6 @@ class Setting(object):
|
|||||||
nargs = None
|
nargs = None
|
||||||
const = None
|
const = None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
if self.default is not None:
|
if self.default is not None:
|
||||||
self.set(self.default)
|
self.set(self.default)
|
||||||
|
|||||||
@ -202,8 +202,8 @@ class Logger(object):
|
|||||||
fileConfig(cfg.logconfig, defaults=CONFIG_DEFAULTS,
|
fileConfig(cfg.logconfig, defaults=CONFIG_DEFAULTS,
|
||||||
disable_existing_loggers=False)
|
disable_existing_loggers=False)
|
||||||
else:
|
else:
|
||||||
raise RuntimeError("Error: log config '%s' not found" %
|
msg = "Error: log config '%s' not found"
|
||||||
cfg.logconfig)
|
raise RuntimeError(msg % cfg.logconfig)
|
||||||
|
|
||||||
def critical(self, msg, *args, **kwargs):
|
def critical(self, msg, *args, **kwargs):
|
||||||
self.error_log.critical(msg, *args, **kwargs)
|
self.error_log.critical(msg, *args, **kwargs)
|
||||||
|
|||||||
@ -82,7 +82,6 @@ class Statsd(Logger):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
# access logging
|
# access logging
|
||||||
def access(self, resp, req, environ, request_time):
|
def access(self, resp, req, environ, request_time):
|
||||||
"""Measure request duration
|
"""Measure request duration
|
||||||
|
|||||||
@ -24,8 +24,8 @@ class Pidfile(object):
|
|||||||
if oldpid:
|
if oldpid:
|
||||||
if oldpid == os.getpid():
|
if oldpid == os.getpid():
|
||||||
return
|
return
|
||||||
raise RuntimeError("Already running on PID %s " \
|
msg = "Already running on PID %s (or pid file '%s' is stale)"
|
||||||
"(or pid file '%s' is stale)" % (oldpid, self.fname))
|
raise RuntimeError(msg % (oldpid, self.fname))
|
||||||
|
|
||||||
self.pid = pid
|
self.pid = pid
|
||||||
|
|
||||||
|
|||||||
@ -70,8 +70,8 @@ except ImportError:
|
|||||||
try:
|
try:
|
||||||
dot = package.rindex('.', 0, dot)
|
dot = package.rindex('.', 0, dot)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValueError("attempted relative import beyond top-level "
|
msg = "attempted relative import beyond top-level package"
|
||||||
"package")
|
raise ValueError(msg)
|
||||||
return "%s.%s" % (package[:dot], name)
|
return "%s.%s" % (package[:dot], name)
|
||||||
|
|
||||||
def import_module(name, package=None):
|
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)
|
return pkg_resources.load_entry_point(dist, section, name)
|
||||||
except:
|
except:
|
||||||
exc = traceback.format_exc()
|
exc = traceback.format_exc()
|
||||||
raise RuntimeError("class uri %r invalid or not found: \n\n[%s]" % (uri,
|
msg = "class uri %r invalid or not found: \n\n[%s]"
|
||||||
exc))
|
raise RuntimeError(msg % (uri, exc))
|
||||||
else:
|
else:
|
||||||
components = uri.split('.')
|
components = uri.split('.')
|
||||||
if len(components) == 1:
|
if len(components) == 1:
|
||||||
@ -130,8 +130,8 @@ def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
|
|||||||
section, uri)
|
section, uri)
|
||||||
except:
|
except:
|
||||||
exc = traceback.format_exc()
|
exc = traceback.format_exc()
|
||||||
raise RuntimeError("class uri %r invalid or not found: \n\n[%s]" % (uri,
|
msg = "class uri %r invalid or not found: \n\n[%s]"
|
||||||
exc))
|
raise RuntimeError(msg % (uri, exc))
|
||||||
|
|
||||||
klass = components.pop(-1)
|
klass = components.pop(-1)
|
||||||
|
|
||||||
@ -139,9 +139,8 @@ def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
|
|||||||
mod = import_module('.'.join(components))
|
mod = import_module('.'.join(components))
|
||||||
except:
|
except:
|
||||||
exc = traceback.format_exc()
|
exc = traceback.format_exc()
|
||||||
raise RuntimeError(
|
msg = "class uri %r invalid or not found: \n\n[%s]"
|
||||||
"class uri %r invalid or not found: \n\n[%s]" %
|
raise RuntimeError(msg % (uri, exc))
|
||||||
(uri, exc))
|
|
||||||
return getattr(mod, klass)
|
return getattr(mod, klass)
|
||||||
|
|
||||||
|
|
||||||
@ -230,7 +229,6 @@ def parse_address(netloc, default_port=8000):
|
|||||||
if netloc.startswith("tcp://"):
|
if netloc.startswith("tcp://"):
|
||||||
netloc = netloc.split("tcp://")[1]
|
netloc = netloc.split("tcp://")[1]
|
||||||
|
|
||||||
|
|
||||||
# get host
|
# get host
|
||||||
if '[' in netloc and ']' in netloc:
|
if '[' in netloc and ']' in netloc:
|
||||||
host = netloc.split(']')[0][1:].lower()
|
host = netloc.split(']')[0][1:].lower()
|
||||||
@ -356,8 +354,8 @@ def import_app(module):
|
|||||||
__import__(module)
|
__import__(module)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
if module.endswith(".py") and os.path.exists(module):
|
if module.endswith(".py") and os.path.exists(module):
|
||||||
raise ImportError("Failed to find application, did "
|
msg = "Failed to find application, did you mean '%s:%s'?"
|
||||||
"you mean '%s:%s'?" % (module.rsplit(".", 1)[0], obj))
|
raise ImportError(msg % (module.rsplit(".", 1)[0], obj))
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|||||||
@ -12,9 +12,10 @@ import sys
|
|||||||
from gunicorn import util
|
from gunicorn import util
|
||||||
from gunicorn.workers.workertmp import WorkerTmp
|
from gunicorn.workers.workertmp import WorkerTmp
|
||||||
from gunicorn.reloader import Reloader
|
from gunicorn.reloader import Reloader
|
||||||
from gunicorn.http.errors import InvalidHeader, InvalidHeaderName, \
|
from gunicorn.http.errors import (
|
||||||
InvalidRequestLine, InvalidRequestMethod, InvalidHTTPVersion, \
|
InvalidHeader, InvalidHeaderName, InvalidRequestLine, InvalidRequestMethod,
|
||||||
LimitRequestLine, LimitRequestHeaders
|
InvalidHTTPVersion, LimitRequestLine, LimitRequestHeaders,
|
||||||
|
)
|
||||||
from gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest
|
from gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest
|
||||||
from gunicorn.http.wsgi import default_environ, Response
|
from gunicorn.http.wsgi import default_environ, Response
|
||||||
from gunicorn.six import MAXSIZE
|
from gunicorn.six import MAXSIZE
|
||||||
@ -22,7 +23,7 @@ from gunicorn.six import MAXSIZE
|
|||||||
|
|
||||||
class Worker(object):
|
class Worker(object):
|
||||||
|
|
||||||
SIGNALS = [getattr(signal, "SIG%s" % x) \
|
SIGNALS = [getattr(signal, "SIG%s" % x)
|
||||||
for x in "ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD".split()]
|
for x in "ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD".split()]
|
||||||
|
|
||||||
PIPE = []
|
PIPE = []
|
||||||
@ -159,7 +160,7 @@ class Worker(object):
|
|||||||
if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,
|
if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,
|
||||||
InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
|
InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
|
||||||
LimitRequestLine, LimitRequestHeaders,
|
LimitRequestLine, LimitRequestHeaders,
|
||||||
InvalidProxyLine, ForbiddenProxyRequest,)):
|
InvalidProxyLine, ForbiddenProxyRequest)):
|
||||||
|
|
||||||
status_int = 400
|
status_int = 400
|
||||||
reason = "Bad Request"
|
reason = "Bad Request"
|
||||||
@ -185,11 +186,8 @@ class Worker(object):
|
|||||||
mesg = "Request forbidden"
|
mesg = "Request forbidden"
|
||||||
status_int = 403
|
status_int = 403
|
||||||
|
|
||||||
self.log.debug("Invalid request from ip={ip}: {error}"\
|
msg = "Invalid request from ip={ip}: {error}"
|
||||||
"".format(ip=addr[0],
|
self.log.debug(msg.format(ip=addr[0], error=str(exc)))
|
||||||
error=str(exc),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
self.log.exception("Error handling request")
|
self.log.exception("Error handling request")
|
||||||
|
|
||||||
|
|||||||
@ -74,7 +74,6 @@ class GeventWorker(AsyncWorker):
|
|||||||
_sock=s))
|
_sock=s))
|
||||||
self.sockets = sockets
|
self.sockets = sockets
|
||||||
|
|
||||||
|
|
||||||
def notify(self):
|
def notify(self):
|
||||||
super(GeventWorker, self).notify()
|
super(GeventWorker, self).notify()
|
||||||
if self.ppid != os.getppid():
|
if self.ppid != os.getppid():
|
||||||
|
|||||||
@ -70,7 +70,6 @@ class TConn(object):
|
|||||||
self.sock = ssl.wrap_socket(client, server_side=True,
|
self.sock = ssl.wrap_socket(client, server_side=True,
|
||||||
**self.cfg.ssl_options)
|
**self.cfg.ssl_options)
|
||||||
|
|
||||||
|
|
||||||
# initialize the parser
|
# initialize the parser
|
||||||
self.parser = http.RequestParser(self.cfg, self.sock)
|
self.parser = http.RequestParser(self.cfg, self.sock)
|
||||||
return True
|
return True
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user