Created
January 19, 2018 09:55
-
-
Save pyk/41cfd1f63db02490c50e241dc501eb92 to your computer and use it in GitHub Desktop.
Sanic Fire & Forget
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sanic import Sanic | |
from sanic import response | |
import asyncio | |
api = Sanic(__name__) | |
@api.listener("before_server_start") | |
async def initialize_tasks_set(api, loop): | |
api.tasks = set() | |
async def busy_work(second): | |
await asyncio.sleep(second) | |
print("busy_work is DONE") | |
@api.get("/") | |
async def index(request): | |
await busy_work(10) | |
return response.json({"status": "ok"}) | |
@api.get("/hello") | |
async def hello(request): | |
return response.json({"status": "ok"}) | |
@api.get("/fire") | |
async def fire(request): | |
future = asyncio.ensure_future(busy_work(10)) | |
api.tasks.add(future) | |
future.add_done_callback(api.tasks.remove) | |
return response.json({"status": "ok"}) | |
@api.listener("after_server_stop") | |
async def wait_pending_busy_work(api, loop): | |
print("waiting busy work") | |
if len(api.tasks) > 0: | |
await asyncio.wait(api.tasks, loop=loop) | |
print("all busy work is done") | |
if __name__ == "__main__": | |
api.run(workers=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment