« Back to Index

Python aiohttp example using mustache (also consider https://github.com/saghul/aiodns)

View original Gist on GitHub

Python aiohttp example using mustache.py

#!/usr/bin/env python
import asyncio

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

from aiohttp import web, get
import ujson
import pystache

TEMPLATE = open('./template.mustache').read()

async def fetch_json(url):
    respone = await get(url)
    data = await respone.json(loads=ujson.loads)
    await respone.release()
    return data


async def handler(request):
    requests = [fetch_json('https://www.example.com/some/api') for _ in range(3)]
    results = await asyncio.gather(*requests)
    badge = next(iter(results))
    body = pystache.render(TEMPLATE, badge)
    return web.Response(text=body, content_type='text/html')

async def health(r):
    return web.Response(text='OK')


def get_app():
    app = web.Application(debug=True)
    app.router.add_get(r'/', handler)
    app.router.add_get(r'/health', health)
    return app


if __name__ == '__main__':
    app = get_app()
    web.run_app(app, port=8080)

requirements.txt

aiohttp==1.1.6
async-timeout==1.1.0
cchardet==1.1.1
chardet==2.3.0
multidict==2.1.4
pystache==0.5.4
tornado==4.4.2
ujson==1.35
uvloop==0.6.7
yarl==0.8.1

template.mustache

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Perf testing</title>
  </head>
  <body>
    <p>{{success}}</p>
    {{#data}}
      <p>{{name}}</p>
      <p>{{path}}</p>
      <p>{{category}}</p>
    {{/data}}
  </body>
</html>