app_rsgi.py 3.8 KB

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