app.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from functools import partial
  2. from random import randint
  3. from emmett import App, request
  4. from emmett.orm import Database, Model, Field, rowmethod
  5. from emmett.tools import service
  6. app = App(__name__)
  7. class World(Model):
  8. tablename = "world"
  9. randomnumber = Field.int()
  10. @rowmethod('serialize')
  11. def _serialize(self, row):
  12. return {'id': row.id, 'randomNumber': row.randomnumber}
  13. class Fortune(Model):
  14. tablename = "fortune"
  15. message = Field.string()
  16. @rowmethod('serialize')
  17. def _serialize(self, row):
  18. return {'id': row.id, 'message': row.message}
  19. app.config.handle_static = False
  20. app.config.db.adapter = 'postgres:psycopg2'
  21. app.config.db.host = 'tfb-database'
  22. app.config.db.user = 'benchmarkdbuser'
  23. app.config.db.password = 'benchmarkdbpass'
  24. app.config.db.database = 'hello_world'
  25. app.config.db.pool_size = 10
  26. db = Database(app)
  27. db.define_models(World, Fortune)
  28. @app.route()
  29. @service.json
  30. async def json():
  31. return {'message': 'Hello, World!'}
  32. @app.route("/db", pipeline=[db.pipe])
  33. @service.json
  34. async def get_random_world():
  35. return World.get(randint(1, 10000)).serialize()
  36. def get_qparam():
  37. try:
  38. rv = int(request.query_params.queries or 1)
  39. except ValueError:
  40. return 1
  41. if rv < 1:
  42. return 1
  43. if rv > 500:
  44. return 500
  45. return rv
  46. @app.route("/queries", pipeline=[db.pipe])
  47. @service.json
  48. async def get_random_worlds():
  49. num_queries = get_qparam()
  50. worlds = [
  51. World.get(randint(1, 10000)).serialize() for _ in range(num_queries)]
  52. return worlds
  53. @app.route(pipeline=[db.pipe], output='template')
  54. async def fortunes():
  55. fortunes = Fortune.all().select()
  56. fortunes.append(
  57. Fortune.new(id=0, message="Additional fortune added at request time."))
  58. fortunes.sort(lambda m: m.message)
  59. return {'fortunes': fortunes}
  60. @app.route(pipeline=[db.pipe])
  61. @service.json
  62. async def updates():
  63. num_queries = get_qparam()
  64. worlds = []
  65. rp = partial(randint, 1, 10000)
  66. ids = [rp() for _ in range(num_queries)]
  67. ids.sort() # To avoid deadlock
  68. for id in ids:
  69. world = World.get(id)
  70. world.update_record(randomnumber=rp())
  71. worlds.append(world.serialize())
  72. return worlds
  73. @app.route(output='bytes')
  74. async def plaintext():
  75. return b'Hello, World!'