app_asgi.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import asyncio
  2. import os
  3. from operator import itemgetter
  4. from pathlib import Path
  5. from random import randint
  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_RESPONSE = {
  23. 'type': 'http.response.start',
  24. 'status': 200,
  25. 'headers': [
  26. [b'content-type', b'application/json'],
  27. ]
  28. }
  29. HTML_RESPONSE = {
  30. 'type': 'http.response.start',
  31. 'status': 200,
  32. 'headers': [
  33. [b'content-type', b'text/html; charset=utf-8'],
  34. ]
  35. }
  36. PLAINTEXT_RESPONSE = {
  37. 'type': 'http.response.start',
  38. 'status': 200,
  39. 'headers': [
  40. [b'content-type', b'text/plain; charset=utf-8'],
  41. ]
  42. }
  43. pool = None
  44. key = itemgetter(1)
  45. json_dumps = orjson.dumps
  46. with Path('templates/fortune.html').open('r') as f:
  47. template = jinja2.Template(f.read())
  48. asyncio.get_event_loop().run_until_complete(pg_setup())
  49. def get_num_queries(scope):
  50. try:
  51. query_string = scope['query_string']
  52. query_count = int(parse_qs(query_string)['queries'][0])
  53. except (KeyError, IndexError, ValueError):
  54. return 1
  55. if query_count < 1:
  56. return 1
  57. if query_count > 500:
  58. return 500
  59. return query_count
  60. async def route_json(scope, receive, send):
  61. await send(JSON_RESPONSE)
  62. await send({
  63. 'type': 'http.response.body',
  64. 'body': json_dumps({'message': 'Hello, world!'}),
  65. 'more_body': False
  66. })
  67. async def route_db(scope, receive, send):
  68. row_id = randint(1, 10000)
  69. connection = await pool.acquire()
  70. try:
  71. number = await connection.fetchval(SQL_SELECT, row_id)
  72. world = {'id': row_id, 'randomNumber': number}
  73. finally:
  74. await pool.release(connection)
  75. await send(JSON_RESPONSE)
  76. await send({
  77. 'type': 'http.response.body',
  78. 'body': json_dumps(world),
  79. 'more_body': False
  80. })
  81. async def route_queries(scope, receive, send):
  82. num_queries = get_num_queries(scope)
  83. row_ids = [randint(1, 10000) for _ in range(num_queries)]
  84. worlds = []
  85. connection = await pool.acquire()
  86. try:
  87. statement = await connection.prepare(SQL_SELECT)
  88. for row_id in row_ids:
  89. number = await statement.fetchval(row_id)
  90. worlds.append({'id': row_id, 'randomNumber': number})
  91. finally:
  92. await pool.release(connection)
  93. await send(JSON_RESPONSE)
  94. await send({
  95. 'type': 'http.response.body',
  96. 'body': json_dumps(worlds),
  97. 'more_body': False
  98. })
  99. async def route_fortunes(scope, receive, send):
  100. connection = await pool.acquire()
  101. try:
  102. fortunes = await connection.fetch('SELECT * FROM Fortune')
  103. finally:
  104. await pool.release(connection)
  105. fortunes.append(ROW_ADD)
  106. fortunes.sort(key=key)
  107. content = template.render(fortunes=fortunes).encode('utf-8')
  108. await send(HTML_RESPONSE)
  109. await send({
  110. 'type': 'http.response.body',
  111. 'body': content,
  112. 'more_body': False
  113. })
  114. async def route_updates(scope, receive, send):
  115. num_queries = get_num_queries(scope)
  116. updates = [(randint(1, 10000), randint(1, 10000)) for _ in range(num_queries)]
  117. worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]
  118. connection = await pool.acquire()
  119. try:
  120. statement = await connection.prepare(SQL_SELECT)
  121. for row_id, _ in updates:
  122. await statement.fetchval(row_id)
  123. await connection.executemany(SQL_UPDATE, updates)
  124. finally:
  125. await pool.release(connection)
  126. await send(JSON_RESPONSE)
  127. await send({
  128. 'type': 'http.response.body',
  129. 'body': json_dumps(worlds),
  130. 'more_body': False
  131. })
  132. async def route_plaintext(scope, receive, send):
  133. await send(PLAINTEXT_RESPONSE)
  134. await send({
  135. 'type': 'http.response.body',
  136. 'body': b'Hello, world!',
  137. 'more_body': False
  138. })
  139. async def handle_404(scope, receive, send):
  140. await send(PLAINTEXT_RESPONSE)
  141. await send({
  142. 'type': 'http.response.body',
  143. 'body': b'Not found',
  144. 'more_body': False
  145. })
  146. routes = {
  147. '/json': route_json,
  148. '/db': route_db,
  149. '/queries': route_queries,
  150. '/fortunes': route_fortunes,
  151. '/updates': route_updates,
  152. '/plaintext': route_plaintext
  153. }
  154. def main(scope, receive, send):
  155. handler = routes.get(scope['path'], handle_404)
  156. return handler(scope, receive, send)