app.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import multiprocessing
  2. import os
  3. from random import randint
  4. from operator import itemgetter
  5. from vibora import Vibora, Request, JsonResponse, Response
  6. from vibora.hooks import Events
  7. from db import Pool
  8. DEFAULT_POOL_SIZE = 1000//multiprocessing.cpu_count()
  9. READ_ROW_SQL = 'SELECT * FROM "world" WHERE id={0}'
  10. WRITE_ROW_SQL = 'UPDATE "world" SET "randomnumber"={0} WHERE id={1} RETURNING id, randomNumber'
  11. READ_ALL_FORTUNES = 'SELECT * FROM "fortune"'
  12. ADDITIONAL_ROW = [0, 'Additional fortune added at request time.']
  13. sort_fortunes_key = itemgetter(1)
  14. app = Vibora(template_dirs=['templates'])
  15. @app.handle(Events.BEFORE_SERVER_START)
  16. async def init_db(app: Vibora):
  17. app.components.add(await Pool("postgresql://%s:%s@%s:5432/%s" % (os.getenv("PGUSER", "benchmarkdbuser"), os.getenv("PSPASS", "benchmarkdbpass"), os.getenv("PGADDR", "tfb-database"), os.getenv("PGDB", "hello_world")), max_size=int(os.getenv("PGPOOLSIZE", DEFAULT_POOL_SIZE))))
  18. @app.handle(Events.BEFORE_SERVER_STOP)
  19. async def close_db(app: Vibora):
  20. await asyncio.wait_for(app.components.get(Pool).close(), timeout=10)
  21. def getQueriesTotal(params):
  22. try:
  23. queries = params['queries'][0]
  24. query_count = int(queries)
  25. except:
  26. return 1
  27. if query_count < 1:
  28. return 1
  29. if query_count > 500:
  30. return 500
  31. return query_count
  32. async def fetchWorld(pool):
  33. async with pool.acquire() as conn:
  34. return await conn.fetchrow(READ_ROW_SQL.format(randint(1, 10000)))
  35. async def updateWorld(world_id, pool):
  36. async with pool.acquire() as conn:
  37. return await conn.fetchrow(WRITE_ROW_SQL.format(randint(1, 10000), world_id))
  38. async def fetchMultipleWorlds(total, pool):
  39. worlds = []
  40. for x in range(total):
  41. res = await fetchWorld(pool)
  42. worlds.append({'id': res[0], 'randomNumber': res[1]})
  43. return worlds
  44. async def updateMultipleWorlds(total, pool):
  45. worlds = []
  46. for x in range(total):
  47. res = await fetchWorld(pool)
  48. updated = await updateWorld(res[0], pool)
  49. worlds.append({'id': updated[0], 'randomNumber': updated[1]})
  50. return worlds
  51. async def fetchFortunes(pool):
  52. async with pool.acquire() as conn:
  53. return await conn.fetch(READ_ALL_FORTUNES)
  54. @app.route('/fortunes')
  55. async def fortunes(pool: Pool):
  56. fortunes = await fetchFortunes(pool)
  57. fortunes.append(ADDITIONAL_ROW)
  58. fortunes.sort(key=sort_fortunes_key)
  59. return await app.render('index.html', fortunes=fortunes)
  60. @app.route('/db')
  61. async def single_query(request: Request, pool: Pool):
  62. res = await fetchWorld(pool)
  63. return JsonResponse({'id': res[0], 'randomNumber': res[1]}, headers={'Server': 'Vibora'})
  64. @app.route('/plaintext')
  65. async def plaintext():
  66. return Response(b'Hello, World!', headers={'Server': 'Vibora', 'Content-Type': 'text/plain'})
  67. @app.route('/json')
  68. async def json():
  69. return JsonResponse({'message': 'Hello, World!'}, headers={'Server': 'Vibora'})
  70. @app.route('/queries')
  71. async def multiple_queries(request: Request, pool: Pool):
  72. total_queries = getQueriesTotal(request.args)
  73. worlds = await fetchMultipleWorlds(total_queries, pool)
  74. return JsonResponse(worlds, headers={'Server': 'Vibora', 'Content-Type': 'application/json', 'Content-Length': str(total_queries)})
  75. @app.route('/updates')
  76. async def update_queries(request: Request, pool: Pool):
  77. total_queries = getQueriesTotal(request.args)
  78. worlds = await updateMultipleWorlds(total_queries, pool)
  79. return JsonResponse(worlds, headers={'Server': 'Vibora', 'Content-Type': 'application/json', 'Content-Length': str(total_queries)})
  80. if __name__ == '__main__':
  81. app.run(host="0.0.0.0", port=8000, workers=multiprocessing.cpu_count())