app.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import asyncio
  2. import asyncpg
  3. import jinja2
  4. import os
  5. import ujson as json
  6. from operator import itemgetter
  7. async def setup():
  8. global pool
  9. pool = await asyncpg.create_pool(
  10. user=os.getenv('PGUSER', 'benchmarkdbuser'),
  11. password=os.getenv('PGPASS', 'benchmarkdbpass'),
  12. database='hello_world',
  13. host=os.getenv('DBHOST', 'localhost'),
  14. port=5432
  15. )
  16. pool = None
  17. additional = [0, 'Additional fortune added at request time.']
  18. key = itemgetter(1)
  19. template = None
  20. path = os.path.join('templates', 'fortune.html')
  21. with open(path, 'r') as template_file:
  22. template_text = template_file.read()
  23. template = jinja2.Template(template_text)
  24. loop = asyncio.get_event_loop()
  25. loop.run_until_complete(setup())
  26. async def json_endpoint(message, channels):
  27. content = json.dumps({'message': 'Hello, world!'}).encode('utf-8')
  28. await channels['reply'].send({
  29. 'status': 200,
  30. 'headers': [
  31. [b'content-type', b'application/json'],
  32. ],
  33. 'content': content
  34. })
  35. async def fortunes_endpoint(message, channels):
  36. connection = await pool.acquire()
  37. try:
  38. fortunes = await connection.fetch('SELECT * FROM Fortune')
  39. fortunes.append(additional)
  40. fortunes.sort(key=key)
  41. content = template.render(fortunes=fortunes).encode('utf-8')
  42. await channels['reply'].send({
  43. 'status': 200,
  44. 'headers': [
  45. [b'content-type', b'text/html; charset=utf-8'],
  46. ],
  47. 'content': content
  48. })
  49. finally:
  50. await pool.release(connection)
  51. async def plaintext_endpoint(message, channels):
  52. await channels['reply'].send({
  53. 'status': 200,
  54. 'headers': [
  55. [b'content-type', b'text/plain'],
  56. ],
  57. 'content': b'Hello, world!'
  58. })
  59. async def handle_404(message, channels):
  60. await channels['reply'].send({
  61. 'status': 404,
  62. 'headers': [
  63. [b'content-type', b'text/plain'],
  64. ],
  65. 'content': b'Not found'
  66. })
  67. routes = {
  68. '/json': json_endpoint,
  69. '/fortunes': fortunes_endpoint,
  70. '/plaintext': plaintext_endpoint
  71. }
  72. async def main(message, channels):
  73. path = message['path']
  74. await routes.get(path, handle_404)(message, channels)