sanic/examples/run_async.py

32 lines
593 B
Python
Raw Normal View History

2017-01-24 03:58:37 +00:00
import asyncio
from signal import SIGINT, signal
2017-02-04 07:27:46 +00:00
import uvloop
2017-01-24 03:58:37 +00:00
from sanic import Sanic, response
2017-01-24 03:58:37 +00:00
app = Sanic(__name__)
2017-01-24 03:58:37 +00:00
@app.route("/")
async def test(request):
2017-04-06 19:39:54 +01:00
return response.json({"answer": "42"})
2017-01-24 03:58:37 +00:00
2017-02-04 07:27:46 +00:00
asyncio.set_event_loop(uvloop.new_event_loop())
server = app.create_server(
host="0.0.0.0", port=8000, return_asyncio_server=True
)
2017-01-24 03:58:37 +00:00
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(server)
server = loop.run_until_complete(task)
loop.run_until_complete(server.startup())
2017-02-04 07:27:46 +00:00
signal(SIGINT, lambda s, f: loop.stop())
2017-01-24 03:58:37 +00:00
try:
loop.run_forever()
finally:
2017-01-24 03:58:37 +00:00
loop.stop()