Skip to content

Commit

Permalink
black and lint
Browse files Browse the repository at this point in the history
  • Loading branch information
mdipierro committed Oct 8, 2023
1 parent 397cfab commit 52df54d
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 160 deletions.
14 changes: 2 additions & 12 deletions py4web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,5 @@ def _maybe_gevent():
from .core import Translator # from pluralize
from .core import action # main py4web decorator
from .core import render # yatl
from .core import (
DAL,
Cache,
Condition,
Flash,
Session,
abort,
check_compatible,
redirect,
request,
response,
)
from .core import (DAL, Cache, Condition, Flash, Session, abort,
check_compatible, redirect, request, response)
3 changes: 1 addition & 2 deletions py4web/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import uuid
import zipfile
from collections import OrderedDict
from contextlib import redirect_stdout, redirect_stderr
from contextlib import redirect_stderr, redirect_stdout

import portalocker
from watchgod import awatch
Expand All @@ -49,7 +49,6 @@
gunicorn = None

import click

# Third party modules
import ombott as bottle
import pluralize
Expand Down
97 changes: 59 additions & 38 deletions py4web/server_adapters.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import os
import sys
import ssl
import sys

from ombott.server_adapters import ServerAdapter

Expand All @@ -12,8 +12,10 @@

__all__ = [
"gevent",
"geventWebSocketServer", "geventWs", # short_name
"wsgirefThreadingServer", "wsgiTh", # short_name
"geventWebSocketServer",
"geventWs", # short_name
"wsgirefThreadingServer",
"wsgiTh", # short_name
"rocketServer",
] + wsservers_list

Expand All @@ -22,10 +24,10 @@
# export PY4WEB_LOGS=/tmp # export PY4WEB_LOGS=
def get_log_file():
log_dir = os.environ.get("PY4WEB_LOGS", None)
log_file = os.path.join (log_dir, 'server-py4web.log') if log_dir else None
log_file = os.path.join(log_dir, "server-py4web.log") if log_dir else None
if log_file:
print(f"log_file: {log_file}")
return log_file
return log_file


def check_level(level):
Expand Down Expand Up @@ -55,29 +57,25 @@ def check_level(level):
)


def logging_conf(level=logging.WARN, logger_name=__name__, test_log = False):
def logging_conf(level=logging.WARN, logger_name=__name__, test_log=False):

log_file = get_log_file()
log_to = dict()

if log_file:
if sys.version_info >= (3, 9):
log_to["filename" ] = log_file
log_to["filemode" ] = "w"
log_to["filename"] = log_file
log_to["filemode"] = "w"
log_to["encoding"] = "utf-8"
else:
h = logging.FileHandler(
log_file,
mode = "w",
encoding = "utf-8"
)
log_to.update( {"handlers": [h]} )
else:
h = logging.FileHandler(log_file, mode="w", encoding="utf-8")
log_to.update({"handlers": [h]})

short_msg = "%(message)s > %(threadName)s > %(asctime)s.%(msecs)03d"
#long_msg = short_msg + " > %(funcName)s > %(filename)s:%(lineno)d > %(levelname)s"
# long_msg = short_msg + " > %(funcName)s > %(filename)s:%(lineno)d > %(levelname)s"

time_msg = '%H:%M:%S'
#date_time_msg = '%Y-%m-%d %H:%M:%S'
time_msg = "%H:%M:%S"
# date_time_msg = '%Y-%m-%d %H:%M:%S'

try:
logging.basicConfig(
Expand All @@ -86,10 +84,13 @@ def logging_conf(level=logging.WARN, logger_name=__name__, test_log = False):
level=check_level(level),
**log_to,
)
except ( OSError, LookupError, KeyError, ValueError ) as ex:
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),)
print(f"cannot open {log_file}")
logging.basicConfig(
format="%(message)s",
level=check_level(level),
)

if logger_name is None:
return None
Expand All @@ -98,8 +99,14 @@ def logging_conf(level=logging.WARN, logger_name=__name__, test_log = False):
log.propagate = True

if test_log:
for func in (log.debug, log.info, log.warn, log.error, log.critical, ) :
func('func: ' + func.__name__ )
for func in (
log.debug,
log.info,
log.warn,
log.error,
log.critical,
):
func("func: " + func.__name__)

return log

Expand All @@ -110,12 +117,15 @@ def get_workers(opts, default=10):
except KeyError:
return default


# ---------------------- servers -----------------------------------------------


def gevent():
# gevent version 23.9.1

import threading

from gevent import local, pywsgi # pip install gevent

if not isinstance(threading.local(), local.local):
Expand All @@ -129,13 +139,14 @@ def gevent():

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

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

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

Expand All @@ -156,7 +167,7 @@ def run(self, app_handler):
app_handler,
log=logger,
error_log=logger,
**ssl_args
**ssl_args,
)

server.serve_forever()
Expand All @@ -166,7 +177,6 @@ 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 @@ -183,13 +193,14 @@ def geventWebSocketServer():

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

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

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

ssl_args = (
Expand All @@ -207,21 +218,25 @@ def run(self, app_handler):
handler_class=WebSocketHandler,
log=logger,
error_log=logger,
**ssl_args
**ssl_args,
)

server.serve_forever()

return GeventWebSocketServer
geventWs=geventWebSocketServer


geventWs = geventWebSocketServer


def wsgirefThreadingServer():
# https://www.electricmonk.nl/log/2016/02/15/multithreaded-dev-web-server-for-the-python-bottle-web-framework/

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):
Expand All @@ -230,7 +245,8 @@ def run(self, app_handler):

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

self_run = self # used in internal classes to access options and logger
Expand Down Expand Up @@ -306,7 +322,7 @@ def log_message(self, format, *args):
)
self_run.log.info(msg)

#handler_cls = self.options.get("handler_class", LogHandler)
# handler_cls = self.options.get("handler_class", LogHandler)
server_cls = Server

if ":" in self.host: # Fix wsgiref for IPv6 addresses.
Expand All @@ -317,11 +333,16 @@ class ServerClass(Server):

server_cls = ServerClass

srv = make_server(self.host, self.port, app_handler, server_cls, LogHandler ) # handler_cls)
srv = make_server(
self.host, self.port, app_handler, server_cls, LogHandler
) # handler_cls)
srv.serve_forever()

return WSGIRefThreadingServer
wsgiTh=wsgirefThreadingServer


wsgiTh = wsgirefThreadingServer


def rocketServer():
try:
Expand Down
25 changes: 16 additions & 9 deletions py4web/utils/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@
import urllib
import uuid

from pydal.validators import (CRYPT, IS_EMAIL, IS_EQUAL_TO, IS_MATCH,
IS_NOT_EMPTY, IS_NOT_IN_DB, IS_STRONG)
from yatl.helpers import DIV, A

from py4web import HTTP, URL, Field, action, redirect, request, response
from py4web.core import REGEX_APPJSON, Fixture, Flash, Template, Translator
from py4web.utils.form import Form, FormStyleDefault
from py4web.utils.param import Param
from pydal.validators import (CRYPT, IS_EMAIL, IS_EQUAL_TO, IS_MATCH,
IS_NOT_EMPTY, IS_NOT_IN_DB, IS_STRONG)
from yatl.helpers import DIV, A

"""
[X] Enable and disable plugins
Expand Down Expand Up @@ -470,11 +471,17 @@ def signature(self):
@property
def user(self):
"""Use as @action.uses(auth.user)"""
return self.param.auth_enforcer if self.param.auth_enforcer else AuthEnforcer(self)
return (
self.param.auth_enforcer if self.param.auth_enforcer else AuthEnforcer(self)
)

def condition(self, condition):
"""Use as @action.uses(auth.condition(lambda user: True))"""
return self.param.auth_enforcer if self.param.auth_enforcer else AuthEnforcer(self, condition)
return (
self.param.auth_enforcer
if self.param.auth_enforcer
else AuthEnforcer(self, condition)
)

# utilities
def get_user(self, safe=True):
Expand Down Expand Up @@ -976,7 +983,7 @@ def enable(self, route="auth", uses=(), env=None, spa=False, allow_api_routes=Tr
for api_name in AuthAPI.public_api
if self.allows(api_name)
]

# Exposed Private APIs
exposed_api_routes.extend(
[
Expand All @@ -989,15 +996,15 @@ def enable(self, route="auth", uses=(), env=None, spa=False, allow_api_routes=Tr
if self.allows(api_name)
]
)

for item in exposed_api_routes:
api_factory = getattr(AuthAPI, item["api_name"])

@action(item["api_route"], method=methods)
@action.uses(item["uses"], *uses)
def _(auth=auth, api_factory=api_factory):
return api_factory(auth)

# This exposes all plugins as /{app_name}/{route}/plugins/{path}
for name in self.plugins:

Expand Down
Loading

0 comments on commit 52df54d

Please sign in to comment.