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
@ -16,7 +16,7 @@ def load(arg):
|
||||
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)
|
||||
|
||||
@ -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 @@ class GunicornSubProcessTestMiddleware(object):
|
||||
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 @@ LOGGING = {
|
||||
}
|
||||
}
|
||||
|
||||
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 @@ class SubDomainApp:
|
||||
|
||||
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)
|
||||
|
||||
@ -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 тест"),
|
||||
|
||||
@ -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 @@ class MemoryWatch(threading.Thread):
|
||||
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
|
||||
|
||||
|
||||
@ -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 @@ class Arbiter(object):
|
||||
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:
|
||||
|
||||
@ -8,7 +8,7 @@ import grp
|
||||
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 @@ class Config(object):
|
||||
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 @@ class Logger(object):
|
||||
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 @@ except MemoryError:
|
||||
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 @@ class Response(object):
|
||||
|
||||
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 @@ class Statsd(Logger):
|
||||
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)
|
||||
|
||||
@ -24,8 +24,8 @@ class Pidfile(object):
|
||||
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
|
||||
|
||||
|
||||
@ -70,8 +70,8 @@ except ImportError:
|
||||
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,8 +130,8 @@ 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)
|
||||
|
||||
@ -139,9 +139,8 @@ def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
|
||||
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):
|
||||
|
||||
@ -12,9 +12,10 @@ import sys
|
||||
from gunicorn import util
|
||||
from gunicorn.workers.workertmp import WorkerTmp
|
||||
from gunicorn.reloader import Reloader
|
||||
from gunicorn.http.errors import InvalidHeader, InvalidHeaderName, \
|
||||
InvalidRequestLine, InvalidRequestMethod, InvalidHTTPVersion, \
|
||||
LimitRequestLine, LimitRequestHeaders
|
||||
from gunicorn.http.errors import (
|
||||
InvalidHeader, InvalidHeaderName, InvalidRequestLine, InvalidRequestMethod,
|
||||
InvalidHTTPVersion, LimitRequestLine, LimitRequestHeaders,
|
||||
)
|
||||
from gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest
|
||||
from gunicorn.http.wsgi import default_environ, Response
|
||||
from gunicorn.six import MAXSIZE
|
||||
@ -22,7 +23,7 @@ from gunicorn.six import MAXSIZE
|
||||
|
||||
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()]
|
||||
|
||||
PIPE = []
|
||||
@ -157,9 +158,9 @@ class Worker(object):
|
||||
request_start = datetime.now()
|
||||
addr = addr or ('', -1) # unix socket case
|
||||
if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,
|
||||
InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
|
||||
LimitRequestLine, LimitRequestHeaders,
|
||||
InvalidProxyLine, ForbiddenProxyRequest,)):
|
||||
InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
|
||||
LimitRequestLine, LimitRequestHeaders,
|
||||
InvalidProxyLine, ForbiddenProxyRequest)):
|
||||
|
||||
status_int = 400
|
||||
reason = "Bad Request"
|
||||
@ -185,11 +186,8 @@ class Worker(object):
|
||||
mesg = "Request forbidden"
|
||||
status_int = 403
|
||||
|
||||
self.log.debug("Invalid request from ip={ip}: {error}"\
|
||||
"".format(ip=addr[0],
|
||||
error=str(exc),
|
||||
)
|
||||
)
|
||||
msg = "Invalid request from ip={ip}: {error}"
|
||||
self.log.debug(msg.format(ip=addr[0], error=str(exc)))
|
||||
else:
|
||||
self.log.exception("Error handling request")
|
||||
|
||||
|
||||
@ -74,7 +74,6 @@ class GeventWorker(AsyncWorker):
|
||||
_sock=s))
|
||||
self.sockets = sockets
|
||||
|
||||
|
||||
def notify(self):
|
||||
super(GeventWorker, self).notify()
|
||||
if self.ppid != os.getppid():
|
||||
@ -129,7 +128,7 @@ class GeventWorker(AsyncWorker):
|
||||
try:
|
||||
# Stop accepting requests
|
||||
for server in servers:
|
||||
if hasattr(server, 'close'): # gevent 1.0
|
||||
if hasattr(server, 'close'): # gevent 1.0
|
||||
server.close()
|
||||
if hasattr(server, 'kill'): # gevent < 1.0
|
||||
server.kill()
|
||||
|
||||
@ -70,7 +70,6 @@ class TConn(object):
|
||||
self.sock = ssl.wrap_socket(client, server_side=True,
|
||||
**self.cfg.ssl_options)
|
||||
|
||||
|
||||
# initialize the parser
|
||||
self.parser = http.RequestParser(self.cfg, self.sock)
|
||||
return True
|
||||
|
||||
@ -39,4 +39,4 @@ for author in map(str.strip, lines):
|
||||
|
||||
|
||||
with open('result.txt', 'w') as output:
|
||||
output.write('\n'.join(collection))
|
||||
output.write('\n'.join(collection))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user