From 5171cdd305ffde7ebf1e4d23b886489d038795b8 Mon Sep 17 00:00:00 2001 From: Jack Fischer Date: Wed, 26 Oct 2016 16:53:34 -0400 Subject: [PATCH] add example with async http requests --- examples/aiohttp_example.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 examples/aiohttp_example.py diff --git a/examples/aiohttp_example.py b/examples/aiohttp_example.py new file mode 100644 index 00000000..8e7892a7 --- /dev/null +++ b/examples/aiohttp_example.py @@ -0,0 +1,33 @@ +from sanic import Sanic +from sanic.response import json + +import uvloop +import aiohttp + +#Create an event loop manually so that we can use it for both sanic & aiohttp +loop = uvloop.new_event_loop() + +app = Sanic(__name__) + +async def fetch(session, url): + """ + Use session object to perform 'get' request on url + """ + async with session.get(url) as response: + return await response.json() + + +@app.route("/") +async def test(request): + """ + Download and serve example JSON + """ + url = "https://api.github.com/repos/channelcat/sanic" + + async with aiohttp.ClientSession(loop=loop) as session: + response = await fetch(session, url) + return json(response) + + +app.run(host="0.0.0.0", port=8000, loop=loop) +