app_postgres.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import multiprocessing
  2. from wsgiref.handlers import format_date_time
  3. import random
  4. import japronto
  5. import ujson as json
  6. from db import init_db, close_db
  7. def get_headers():
  8. return {
  9. 'Server': 'Japronto/0.1.1',
  10. 'Date': format_date_time(None),
  11. }
  12. def json_view(request):
  13. return request.Response(
  14. text=json.dumps({'message': 'Hello, world!'}),
  15. mime_type='application/json',
  16. headers=get_headers(),
  17. )
  18. def plaintext_view(request):
  19. return request.Response(
  20. body=b'Hello, world!',
  21. mime_type='text/plain',
  22. headers=get_headers(),
  23. )
  24. async def db_view(request):
  25. async with app.db_pool.acquire() as conn:
  26. world = await conn.fetchrow("select id,randomnumber from world where id=%s" % random.randint(1, 10000))
  27. return request.Response(
  28. text=json.dumps(dict(world)),
  29. mime_type='application/json', headers=get_headers())
  30. app = japronto.Application()
  31. app.on_startup.append(init_db)
  32. app.on_cleanup.append(close_db)
  33. app.router.add_route('/json', json_view, 'GET')
  34. app.router.add_route('/plaintext', plaintext_view, 'GET')
  35. app.router.add_route('/db', db_view, 'GET')
  36. if __name__ == '__main__':
  37. app.run('0.0.0.0', 8080, worker_num=multiprocessing.cpu_count())