Merge pull request #411 from r0fls/ensure-future

Ensure future
This commit is contained in:
Eli Uriegas 2017-02-13 17:13:26 -06:00 committed by GitHub
commit a6a07c3b3a
2 changed files with 46 additions and 1 deletions

View File

@ -46,7 +46,6 @@ class Sanic:
self._blueprint_order = [] self._blueprint_order = []
self.debug = None self.debug = None
self.sock = None self.sock = None
self.processes = None
self.listeners = defaultdict(list) self.listeners = defaultdict(list)
# Register alternative method names # Register alternative method names
@ -63,6 +62,22 @@ class Sanic:
# Registration # Registration
# -------------------------------------------------------------------- # # -------------------------------------------------------------------- #
def add_task(self, task):
"""
Schedule a task to run later, after the loop has started.
Different from asyncio.ensure_future in that it does not
also return a future, and the actual ensure_future call
is delayed until before server start.
:param task: A future, couroutine or awaitable.
"""
@self.listener('before_server_start')
def run(app, loop):
if callable(task):
loop.create_task(task())
else:
loop.create_task(task)
# Decorator # Decorator
def listener(self, event): def listener(self, event):
""" """

30
tests/test_create_task.py Normal file
View File

@ -0,0 +1,30 @@
import sanic
from sanic.utils import sanic_endpoint_test
from sanic.response import text
from threading import Event
import asyncio
def test_create_task():
e = Event()
async def coro():
await asyncio.sleep(0.05)
e.set()
app = sanic.Sanic()
app.add_task(coro)
@app.route('/early')
def not_set(request):
return text(e.is_set())
@app.route('/late')
async def set(request):
await asyncio.sleep(0.1)
return text(e.is_set())
request, response = sanic_endpoint_test(app, uri='/early')
assert response.body == b'False'
request, response = sanic_endpoint_test(app, uri='/late')
assert response.body == b'True'