app.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import os
  2. import sys
  3. import multiprocessing
  4. from wsgiref.handlers import format_date_time
  5. import japronto
  6. import ujson as json
  7. import random
  8. import asyncio
  9. import asyncpg
  10. db_pool = None
  11. async def db_setup():
  12. global db_pool
  13. db_pool = await asyncpg.create_pool(
  14. user = os.getenv('PGUSER', 'benchmarkdbuser'),
  15. password = os.getenv('PGPASS', 'benchmarkdbpass'),
  16. database = 'hello_world',
  17. host = 'tfb-database',
  18. port = 5432
  19. )
  20. READ_ROW_SQL = 'SELECT "randomnumber", "id" FROM "world" WHERE id = $1'
  21. def get_headers():
  22. return {
  23. 'Server': 'Japronto/0.1.2',
  24. 'Date': format_date_time(None),
  25. }
  26. # -----------------------------------------------------------------------------------
  27. def json_view(request):
  28. return request.Response(
  29. text = json.dumps( {'message': 'Hello, world!'} ),
  30. mime_type = 'application/json',
  31. headers = get_headers(),
  32. )
  33. def plaintext_view(request):
  34. return request.Response(
  35. body = b'Hello, world!',
  36. mime_type = 'text/plain',
  37. headers = get_headers(),
  38. )
  39. async def db_view(request):
  40. global db_pool
  41. row_id = random.randint(1, 10000)
  42. async with db_pool.acquire() as connection:
  43. number = await connection.fetchval(READ_ROW_SQL, row_id)
  44. text = json.dumps( {'id': row_id, 'randomNumber': number} )
  45. return request.Response(text = text, mime_type = 'application/json', headers = get_headers())
  46. # -----------------------------------------------------------------------------------
  47. app = japronto.Application()
  48. app.router.add_route('/json', json_view, 'GET')
  49. app.router.add_route('/plaintext', plaintext_view, 'GET')
  50. #app.router.add_route('/db', db_view, 'GET')
  51. #asyncio.set_event_loop(app.loop)
  52. #app.loop.run_until_complete(db_setup())
  53. # -----------------------------------------------------------------------------------
  54. if __name__ == '__main__':
  55. _is_travis = os.environ.get('TRAVIS') == 'true'
  56. workers = int( multiprocessing.cpu_count() )
  57. if _is_travis:
  58. workers = 2
  59. app.run('0.0.0.0', 8080, worker_num = workers)