misc.signal_handler: allow unsetting signals, http_server_async: unset signal handlers on stop and handle custom coroutines on start

This commit is contained in:
Izalia Mae 2021-10-25 10:36:11 -04:00
parent 1d6abc61aa
commit cc8f8b09a1
2 changed files with 22 additions and 10 deletions

View file

@ -13,6 +13,7 @@ from .view import Static, Manifest, Robots, Style
from .. import logging
from ..dotdict import DotDict
from ..exceptions import MethodNotHandledException
from ..misc import signal_handler
from ..path import Path
from ..template import Template
@ -24,6 +25,7 @@ class Application:
def __init__(self, loop=None, views=[], middleware=[], **kwargs):
self.loop = loop or asyncio.get_event_loop()
self._server = None
self._tasks = []
self.cfg = Config(**kwargs)
self.router = Router(trim_last_slash=True)
@ -57,11 +59,6 @@ class Application:
else:
self.template = None
signal.signal(signal.SIGHUP, self.stop)
signal.signal(signal.SIGINT, self.stop)
signal.signal(signal.SIGQUIT, self.stop)
signal.signal(signal.SIGTERM, self.stop)
def get_route(self, path, method='GET'):
return self.router(path, method.upper())
@ -132,8 +129,14 @@ class Application:
self._server.close()
for task in self._tasks:
task.cancel()
self._tasks.remove(task)
def start(self, log=True):
signal_handler()
def start(self, *tasks, log=True):
if self._server:
return
@ -157,7 +160,12 @@ class Application:
reuse_port = True
)
signal_handler(self.stop)
self._server = self.loop.run_until_complete(server)
for task in tasks:
asyncio.ensure_future(task, loop=self.loop)
self.loop.run_until_complete(self.handle_run_server())

View file

@ -359,12 +359,16 @@ def remove(string: str, junk: list):
return string
def signal_handler(func, *args, original_args=True, **kwargs):
if original_args:
handler = lambda signum, frame: func(signum, frame, *args, **kwargs)
def signal_handler(func=None, *args, original_args=False, **kwargs):
if func:
if original_args:
handler = lambda signum, frame: func(signum, frame, *args, **kwargs)
else:
handler = lambda *_: func(*args, **kwargs)
else:
handler = lambda *_: func(*args, **kwargs)
handler = signal.SIG_DFL
signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGINT, handler)