Skip to content

Commit

Permalink
black file
Browse files Browse the repository at this point in the history
  • Loading branch information
ali96343 committed Oct 28, 2023
1 parent 57eeac3 commit ebc617f
Showing 1 changed file with 41 additions and 54 deletions.
95 changes: 41 additions & 54 deletions py4web/server_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
# ---------------------- utils -----------------------------------------------

# export PY4WEB_LOGS=/tmp # export PY4WEB_LOGS=
def get_log_file(out_banner = True):
def get_log_file(out_banner=True):
log_dir = os.environ.get("PY4WEB_LOGS", None)
if log_dir and os.path.isdir(log_dir):
log_file = os.path.join (log_dir, 'server-py4web.log')
log_file = os.path.join(log_dir, "server-py4web.log")
if out_banner:
print(f"log_file: {log_file}")
return log_file
Expand Down Expand Up @@ -83,17 +83,13 @@ def logging_conf(level=logging.WARN, logger_name=__name__, test_log=False):

try:
logging.basicConfig(
format=short_msg,
datefmt=time_msg,
level=check_level(level),
**log_to,
format=short_msg, datefmt=time_msg, level=check_level(level), **log_to,
)
except (OSError, LookupError, KeyError, ValueError) as ex:
print(f"{ex}, {__file__}")
print(f"cannot open {log_file}")
logging.basicConfig(
format="%(message)s",
level=check_level(level),
format="%(message)s", level=check_level(level),
)

if logger_name is None:
Expand Down Expand Up @@ -131,39 +127,42 @@ def gunicorn():
# To use gevent monkey.patch_all()
# run ./py4web.py run apps -s gunicornGevent ......
if isinstance(threading.local(), local.local):
print( 'gunicorn: monkey.patch_all() applied' )
print("gunicorn: monkey.patch_all() applied")

class GunicornServer(ServerAdapter):
""" https://docs.gunicorn.org/en/stable/settings.html """

# https://pawamoy.github.io/posts/unify-logging-for-a-gunicorn-uvicorn-app/
# ./py4web.py run apps -s gunicorn --watch=off --port=8000 --ssl_cert=cert.pem --ssl_key=key.pem -w 6 -L 20
#
# ./py4web.py run apps -s gunicornGevent --watch=off --port=8000 --ssl_cert=cert.pem --ssl_key=key.pem -w 6 -L 20
#
# ./py4web.py run apps -s gunicornGevent --watch=off --port=8000 --ssl_cert=cert.pem --ssl_key=key.pem -w 6 -L 20

def run(self, app_handler):
from gunicorn.app.base import BaseApplication

config = {
"bind": f"{self.host}:{self.port}",
"workers": get_workers(self.options),
"certfile": self.options.get("certfile", None),
"keyfile": self.options.get("keyfile", None),
}
"bind": f"{self.host}:{self.port}",
"workers": get_workers(self.options),
"certfile": self.options.get("certfile", None),
"keyfile": self.options.get("keyfile", None),
}

if not self.quiet:

level = check_level (self.options["logging_level"])
log_file = get_log_file ( out_banner= False)
level = check_level(self.options["logging_level"])
log_file = get_log_file(out_banner=False)

logger = logging_conf(level )
log_to = "-" if log_file is None else log_file
logger = logging_conf(level)
log_to = "-" if log_file is None else log_file

config.update({
"loglevel": logging.getLevelName( level ),
"access_log_format" : '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' ,
"accesslog": log_to,
"errorlog": log_to,
})
config.update(
{
"loglevel": logging.getLevelName(level),
"access_log_format": '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"',
"accesslog": log_to,
"errorlog": log_to,
}
)

class GunicornApplication(BaseApplication):
def load_config(self):
Expand Down Expand Up @@ -195,14 +194,14 @@ def load_config(self):

gunicorn_vars = dict()

for k,v in os.environ.items():
for k, v in os.environ.items():
if k.startswith("GUNICORN_") and v:
key = k.split('_', 1)[1].lower()
key = k.split("_", 1)[1].lower()
gunicorn_vars[key] = v

if gunicorn_vars:
config.update( gunicorn_vars )
print ('gunicorn config:',config)
config.update(gunicorn_vars)
print("gunicorn config:", config)

for key, value in config.items():
self.cfg.set(key, value)
Expand All @@ -211,10 +210,12 @@ def load(self):
return app_handler

GunicornApplication().run()

return GunicornServer
gunicornGevent = gunicorn


gunicornGevent = gunicorn


def gevent():
# gevent version 23.9.1
Expand All @@ -234,13 +235,10 @@ def gevent():

class GeventServer(ServerAdapter):
def run(self, app_handler):
logger = None #"default"
logger = None # "default"

if not self.quiet:
logger = logging_conf(
self.options["logging_level"],
"gevent",
)
logger = logging_conf(self.options["logging_level"], "gevent",)
# logger.addHandler(logging.StreamHandler())

certfile = self.options.get("certfile", None)
Expand Down Expand Up @@ -272,6 +270,7 @@ def run(self, app_handler):

def geventWebSocketServer():
from gevent import pywsgi

# from geventwebsocket.handler import WebSocketHandler # pip install gevent-websocket
from gevent_ws import WebSocketHandler # pip install gevent gevent-ws

Expand All @@ -288,21 +287,15 @@ def geventWebSocketServer():

class GeventWebSocketServer(ServerAdapter):
def run(self, app_handler):
logger = None #"default"
logger = None # "default"

if not self.quiet:
logger = logging_conf(
self.options["logging_level"],
"gevent-ws",
)
logger = logging_conf(self.options["logging_level"], "gevent-ws",)

certfile = self.options.get("certfile", None)

ssl_args = (
dict(
certfile=certfile,
keyfile=self.options.get("keyfile", None),
)
dict(certfile=certfile, keyfile=self.options.get("keyfile", None),)
if certfile
else dict()
)
Expand Down Expand Up @@ -330,19 +323,15 @@ def wsgirefThreadingServer():
import socket
from concurrent.futures import ThreadPoolExecutor # pip install futures
from socketserver import ThreadingMixIn
from wsgiref.simple_server import (WSGIRequestHandler, WSGIServer,
make_server)
from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server

class WSGIRefThreadingServer(ServerAdapter):
def run(self, app_handler):

self.log = None

if not self.quiet:
self.log = logging_conf(
self.options["logging_level"],
"wsgiref",
)
self.log = logging_conf(self.options["logging_level"], "wsgiref",)

self_run = self # used in internal classes to access options and logger

Expand Down Expand Up @@ -450,9 +439,7 @@ def run(self, app_handler):

if not self.quiet:

logging_conf(
self.options["logging_level"],
)
logging_conf(self.options["logging_level"],)

interface = (
(
Expand Down

0 comments on commit ebc617f

Please sign in to comment.