app_rsgi.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import asyncio
  2. import os
  3. from operator import itemgetter
  4. from pathlib import Path
  5. from random import randint, sample
  6. from urllib.parse import parse_qs
  7. import asyncpg
  8. import jinja2
  9. import orjson
  10. async def pg_setup():
  11. global pool
  12. pool = await asyncpg.create_pool(
  13. user=os.getenv('PGUSER', 'benchmarkdbuser'),
  14. password=os.getenv('PGPASS', 'benchmarkdbpass'),
  15. database='hello_world',
  16. host='tfb-database',
  17. port=5432
  18. )
  19. SQL_SELECT = 'SELECT "randomnumber", "id" FROM "world" WHERE id = $1'
  20. SQL_UPDATE = 'UPDATE "world" SET "randomnumber"=$1 WHERE id=$2'
  21. ROW_ADD = [0, 'Additional fortune added at request time.']
  22. JSON_HEADERS = [('content-type', 'application/json')]
  23. HTML_HEADERS = [('content-type', 'text/html; charset=utf-8')]
  24. PLAINTEXT_HEADERS = [('content-type', 'text/plain; charset=utf-8')]
  25. pool = None
  26. key = itemgetter(1)
  27. json_dumps = orjson.dumps
  28. with Path('templates/fortune.html').open('r') as f:
  29. template = jinja2.Template(f.read())
  30. asyncio.get_event_loop().run_until_complete(pg_setup())
  31. def get_num_queries(scope):
  32. try:
  33. query_count = int(parse_qs(scope.query_string)['queries'][0])
  34. except (KeyError, IndexError, ValueError):
  35. return 1
  36. if query_count < 1:
  37. return 1
  38. if query_count > 500:
  39. return 500
  40. return query_count
  41. async def route_json(scope, proto):
  42. proto.response_bytes(
  43. 200,
  44. JSON_HEADERS,
  45. json_dumps({'message': 'Hello, world!'})
  46. )
  47. async def route_db(scope, proto):
  48. row_id = randint(1, 10000)
  49. async with pool.acquire() as connection:
  50. number = await connection.fetchval(SQL_SELECT, row_id)
  51. proto.response_bytes(
  52. 200,
  53. JSON_HEADERS,
  54. json_dumps({'id': row_id, 'randomNumber': number})
  55. )
  56. async def route_queries(scope, proto):
  57. num_queries = get_num_queries(scope)
  58. row_ids = sample(range(1, 10000), num_queries)
  59. worlds = []
  60. async with pool.acquire() as connection:
  61. statement = await connection.prepare(SQL_SELECT)
  62. for row_id in row_ids:
  63. number = await statement.fetchval(row_id)
  64. worlds.append({'id': row_id, 'randomNumber': number})
  65. proto.response_bytes(
  66. 200,
  67. JSON_HEADERS,
  68. json_dumps(worlds)
  69. )
  70. async def route_fortunes(scope, proto):
  71. async with pool.acquire() as connection:
  72. fortunes = await connection.fetch('SELECT * FROM Fortune')
  73. fortunes.append(ROW_ADD)
  74. fortunes.sort(key=key)
  75. content = template.render(fortunes=fortunes)
  76. proto.response_str(
  77. 200,
  78. HTML_HEADERS,
  79. content
  80. )
  81. async def route_updates(scope, proto):
  82. num_queries = get_num_queries(scope)
  83. updates = list(zip(
  84. sample(range(1, 10000), num_queries),
  85. sorted(sample(range(1, 10000), num_queries))
  86. ))
  87. worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]
  88. async with pool.acquire() as connection:
  89. statement = await connection.prepare(SQL_SELECT)
  90. for row_id, _ in updates:
  91. await statement.fetchval(row_id)
  92. await connection.executemany(SQL_UPDATE, updates)
  93. proto.response_bytes(
  94. 200,
  95. JSON_HEADERS,
  96. json_dumps(worlds)
  97. )
  98. async def route_plaintext(scope, proto):
  99. proto.response_bytes(
  100. 200,
  101. PLAINTEXT_HEADERS,
  102. b'Hello, world!'
  103. )
  104. async def handle_404(scope, proto):
  105. proto.response_bytes(
  106. 404,
  107. PLAINTEXT_HEADERS,
  108. b'Not found'
  109. )
  110. routes = {
  111. '/json': route_json,
  112. '/db': route_db,
  113. '/queries': route_queries,
  114. '/fortunes': route_fortunes,
  115. '/updates': route_updates,
  116. '/plaintext': route_plaintext
  117. }
  118. def main(scope, proto):
  119. handler = routes.get(scope.path, handle_404)
  120. return handler(scope, proto)