Remove arguments that pass before_start, before_stop, after_start, after_stop functions, instead use decorators.

Results in cleaner API.
This commit is contained in:
Angus Hollands 2017-02-11 11:53:18 +00:00
parent 75fca1b9c7
commit 810008a73a

View File

@ -20,6 +20,7 @@ from .static import register as static_register
class Sanic: class Sanic:
def __init__(self, name=None, router=None, def __init__(self, name=None, router=None,
error_handler=None): error_handler=None):
# Only set up a default log handler if the # Only set up a default log handler if the
@ -45,6 +46,10 @@ class Sanic:
self.debug = None self.debug = None
self.sock = None self.sock = None
self.processes = None self.processes = None
self._before_start_callbacks = []
self._after_start_callbacks = []
self._before_stop_callbacks = []
self._after_stop_callbacks = []
# Register alternative method names # Register alternative method names
self.go_fast = self.run self.go_fast = self.run
@ -53,6 +58,27 @@ class Sanic:
# Registration # Registration
# -------------------------------------------------------------------- # # -------------------------------------------------------------------- #
# Decorator
def before_start(self, func):
"""Decorates a function to be executed before the server starts accepting connections"""
self._before_start_callbacks.append(func)
# Decorator
def after_start(self, func):
"""Decorates a function to be executed after the server starts accepting connections"""
self._after_start_callbacks.append(func)
# Decorator
def after_stop(self, func):
"""Decorates a function to be executed when all requests are complete"""
self._after_stop_callbacks.append(func)
# Decorator
def before_stop(self, func):
"""Decorates a function to be executed when a stop signal is received before it is respected"""
self._before_stop_callbacks.append(func)
# Decorator # Decorator
def route(self, uri, methods=frozenset({'GET'}), host=None): def route(self, uri, methods=frozenset({'GET'}), host=None):
""" """
@ -367,8 +393,7 @@ class Sanic:
# Execution # Execution
# -------------------------------------------------------------------- # # -------------------------------------------------------------------- #
def run(self, host="127.0.0.1", port=8000, debug=False, before_start=None, def run(self, host="127.0.0.1", port=8000, debug=False, ssl=None,
after_start=None, before_stop=None, after_stop=None, ssl=None,
sock=None, workers=1, loop=None, protocol=HttpProtocol, sock=None, workers=1, loop=None, protocol=HttpProtocol,
backlog=100, stop_event=None, register_sys_signals=True): backlog=100, stop_event=None, register_sys_signals=True):
""" """
@ -378,14 +403,6 @@ class Sanic:
:param host: Address to host on :param host: Address to host on
:param port: Port to host on :param port: Port to host on
:param debug: Enables debug output (slows server) :param debug: Enables debug output (slows server)
:param before_start: Functions to be executed before the server starts
accepting connections
:param after_start: Functions to be executed after the server starts
accepting connections
:param before_stop: Functions to be executed when a stop signal is
received before it is respected
:param after_stop: Functions to be executed when all requests are
complete
:param ssl: SSLContext for SSL encryption of worker(s) :param ssl: SSLContext for SSL encryption of worker(s)
:param sock: Socket for the server to accept connections from :param sock: Socket for the server to accept connections from
:param workers: Number of processes :param workers: Number of processes
@ -397,12 +414,9 @@ class Sanic:
:param protocol: Subclass of asyncio protocol class :param protocol: Subclass of asyncio protocol class
:return: Nothing :return: Nothing
""" """
server_settings = self._helper( server_settings = self._helper(host=host, port=port, debug=debug, ssl=ssl, sock=sock, workers=workers,
host=host, port=port, debug=debug, before_start=before_start, loop=loop, protocol=protocol, backlog=backlog, stop_event=stop_event,
after_start=after_start, before_stop=before_stop, register_sys_signals=register_sys_signals)
after_stop=after_stop, ssl=ssl, sock=sock, workers=workers,
loop=loop, protocol=protocol, backlog=backlog,
stop_event=stop_event, register_sys_signals=register_sys_signals)
try: try:
if workers == 1: if workers == 1:
serve(**server_settings) serve(**server_settings)
@ -417,20 +431,13 @@ class Sanic:
"""This kills the Sanic""" """This kills the Sanic"""
get_event_loop().stop() get_event_loop().stop()
async def create_server(self, host="127.0.0.1", port=8000, debug=False, async def create_server(self, host="127.0.0.1", port=8000, debug=False, ssl=None, sock=None, loop=None,
before_start=None, after_start=None, protocol=HttpProtocol, backlog=100, stop_event=None):
before_stop=None, after_stop=None, ssl=None,
sock=None, loop=None, protocol=HttpProtocol,
backlog=100, stop_event=None):
""" """
Asynchronous version of `run`. Asynchronous version of `run`.
""" """
server_settings = self._helper( server_settings = self._helper(host=host, port=port, debug=debug, ssl=ssl, sock=sock, loop=loop,
host=host, port=port, debug=debug, before_start=before_start, protocol=protocol, backlog=backlog, stop_event=stop_event, run_async=True)
after_start=after_start, before_stop=before_stop,
after_stop=after_stop, ssl=ssl, sock=sock, loop=loop,
protocol=protocol, backlog=backlog, stop_event=stop_event,
run_async=True)
# Serve # Serve
proto = "http" proto = "http"
@ -440,11 +447,8 @@ class Sanic:
return await serve(**server_settings) return await serve(**server_settings)
def _helper(self, host="127.0.0.1", port=8000, debug=False, def _helper(self, host="127.0.0.1", port=8000, debug=False, ssl=None, sock=None, workers=1, loop=None,
before_start=None, after_start=None, before_stop=None, protocol=HttpProtocol, backlog=100, stop_event=None, register_sys_signals=True, run_async=False):
after_stop=None, ssl=None, sock=None, workers=1, loop=None,
protocol=HttpProtocol, backlog=100, stop_event=None,
register_sys_signals=True, run_async=False):
""" """
Helper function used by `run` and `create_server`. Helper function used by `run` and `create_server`.
""" """
@ -482,10 +486,10 @@ class Sanic:
# -------------------------------------------- # # -------------------------------------------- #
for event_name, settings_name, args, reverse in ( for event_name, settings_name, args, reverse in (
("before_server_start", "before_start", before_start, False), ("before_server_start", "before_start", self._before_start_callbacks, False),
("after_server_start", "after_start", after_start, False), ("after_server_start", "after_start", self._after_start_callbacks, False),
("before_server_stop", "before_stop", before_stop, True), ("before_server_stop", "before_stop", self._before_stop_callbacks, True),
("after_server_stop", "after_stop", after_stop, True), ("after_server_stop", "after_stop", self._after_stop_callbacks, True),
): ):
listeners = [] listeners = []
for blueprint in self.blueprints.values(): for blueprint in self.blueprints.values():
@ -493,7 +497,7 @@ class Sanic:
if args: if args:
if callable(args): if callable(args):
args = [args] args = [args]
listeners += args listeners.extend(args)
if reverse: if reverse:
listeners.reverse() listeners.reverse()
# Prepend sanic to the arguments when listeners are triggered # Prepend sanic to the arguments when listeners are triggered