sanic/examples/aiohttp_example.py

27 lines
597 B
Python
Raw Normal View History

2016-10-26 21:53:34 +01:00
from sanic import Sanic
2017-04-06 18:33:29 +01:00
from sanic import response
2016-10-26 21:53:34 +01:00
import aiohttp
app = Sanic(__name__)
2016-10-26 21:53:34 +01:00
async def fetch(session, url):
"""
Use session object to perform 'get' request on url
"""
2017-04-06 18:33:29 +01:00
async with session.get(url) as result:
return await result.json()
2016-10-26 21:53:34 +01:00
2017-04-06 18:33:29 +01:00
@app.route('/')
async def handle_request(request):
2016-10-26 21:53:34 +01:00
url = "https://api.github.com/repos/channelcat/sanic"
2017-04-06 18:33:29 +01:00
async with aiohttp.ClientSession() as session:
2017-04-06 18:33:29 +01:00
result = await fetch(session, url)
return response.json(result)
2016-10-26 21:53:34 +01:00
2017-04-06 18:33:29 +01:00
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000, workers=2)