sanic/examples/aiohttp_example.py

30 lines
623 B
Python
Raw Normal View History

2016-10-26 21:53:34 +01:00
from sanic import Sanic
from sanic.response import json
2017-01-21 19:26:03 +00:00
import asyncio
2016-10-26 21:53:34 +01:00
import aiohttp
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"
2017-01-21 19:26:03 +00:00
async with aiohttp.ClientSession() as session:
2016-10-26 21:53:34 +01:00
response = await fetch(session, url)
return json(response)
2017-01-21 19:26:03 +00:00
app.run(host="0.0.0.0", port=8000, workers=2)