Merge pull request #885 from yunstanford/master

add triggers events when async create_server
This commit is contained in:
Raphael Deem 2017-08-09 15:59:44 -07:00 committed by GitHub
commit df4a149cd0
3 changed files with 35 additions and 0 deletions

View File

@ -636,14 +636,31 @@ class Sanic:
warnings.simplefilter('default') warnings.simplefilter('default')
warnings.warn("stop_event will be removed from future versions.", warnings.warn("stop_event will be removed from future versions.",
DeprecationWarning) DeprecationWarning)
server_settings = self._helper( server_settings = self._helper(
host=host, port=port, debug=debug, ssl=ssl, sock=sock, host=host, port=port, debug=debug, ssl=ssl, sock=sock,
loop=get_event_loop(), protocol=protocol, loop=get_event_loop(), protocol=protocol,
backlog=backlog, run_async=True, backlog=backlog, run_async=True,
has_log=log_config is not None) has_log=log_config is not None)
# Trigger before_start events
await self.trigger_events(
server_settings.get('before_start', []),
server_settings.get('loop')
)
return await serve(**server_settings) return await serve(**server_settings)
async def trigger_events(self, events, loop):
"""Trigger events (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop
"""
for event in events:
result = event(loop)
if isawaitable(result):
await result
async def _run_request_middleware(self, request): async def _run_request_middleware(self, request):
# The if improves speed. I don't know why # The if improves speed. I don't know why
if self.request_middleware: if self.request_middleware:

View File

@ -59,3 +59,20 @@ def test_all_listeners():
start_stop_app(random_name_app) start_stop_app(random_name_app)
for listener_name in AVAILABLE_LISTENERS: for listener_name in AVAILABLE_LISTENERS:
assert random_name_app.name + listener_name == output.pop() assert random_name_app.name + listener_name == output.pop()
async def test_trigger_before_events_create_server():
class MySanicDb:
pass
app = Sanic("test_sanic_app")
@app.listener('before_server_start')
async def init_db(app, loop):
app.db = MySanicDb()
await app.create_server()
assert hasattr(app, "db")
assert isinstance(app.db, MySanicDb)

View File

@ -10,6 +10,7 @@ deps =
coverage coverage
pytest pytest
pytest-cov pytest-cov
pytest-sanic
pytest-sugar pytest-sugar
aiohttp==1.3.5 aiohttp==1.3.5
chardet<=2.3.0 chardet<=2.3.0