app.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!/usr/bin/env python3
  2. import random
  3. import os
  4. import asyncpg
  5. from quart import jsonify, Quart, request, render_template
  6. app = Quart(__name__)
  7. GET_WORLD = "select id, randomnumber from world where id = $1"
  8. UPDATE_WORLD = "update world set randomNumber = $2 where id = $1"
  9. @app.before_serving
  10. async def connect_to_db():
  11. app.db = 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. @app.after_serving
  19. async def disconnect_from_db():
  20. await app.db.close()
  21. @app.get("/json")
  22. async def json():
  23. return {"message": "Hello, World!"}
  24. @app.get("/plaintext")
  25. async def plaintext():
  26. return "Hello, World!", {"Content-Type": "text/plain"}
  27. @app.get("/db")
  28. async def db():
  29. async with app.db.acquire() as conn:
  30. key = random.randint(1, 10000)
  31. number = await conn.fetchval(GET_WORLD, key)
  32. return jsonify({"id": key, "randomNumber": number})
  33. def get_query_count():
  34. try:
  35. num_queries = request.args.get("queries", 1, type=int)
  36. except ValueError:
  37. num_queries = 1
  38. if num_queries < 1:
  39. return 1
  40. if num_queries > 500:
  41. return 500
  42. return num_queries
  43. @app.get("/queries")
  44. async def queries():
  45. queries = get_query_count()
  46. worlds = []
  47. async with app.db.acquire() as conn:
  48. pst = await conn.prepare(GET_WORLD)
  49. for key in random.sample(range(1, 10000), queries):
  50. number = await pst.fetchval(key)
  51. worlds.append({"id": key, "randomNumber": number})
  52. return jsonify(worlds)
  53. @app.get("/updates")
  54. async def updates():
  55. queries = get_query_count()
  56. new_worlds = []
  57. async with app.db.acquire() as conn, conn.transaction():
  58. pst = await conn.prepare(GET_WORLD)
  59. for key in random.sample(range(1, 10000), queries):
  60. await pst.fetchval(key)
  61. new_number = random.randint(1, 10000)
  62. new_worlds.append((key, new_number))
  63. await conn.executemany(UPDATE_WORLD, new_worlds)
  64. return jsonify(
  65. [{"id": key, "randomNumber": new_number} for key, new_number in new_worlds]
  66. )
  67. @app.get("/fortunes")
  68. async def fortunes():
  69. async with app.db.acquire() as conn:
  70. rows = await conn.fetch("select * from fortune")
  71. rows.append((0, "Additional fortune added at request time."))
  72. rows.sort(key=lambda row: row[1])
  73. return await render_template("fortunes.html", fortunes=rows)
  74. if __name__ == "__main__":
  75. app.run(host="0.0.0.0", port=8080)