app.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from bottle import Bottle, route, request, run
  2. from bottle.ext import sqlalchemy
  3. from sqlalchemy import create_engine, Column, Integer
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from random import randint
  6. import ujson
  7. app = Bottle()
  8. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://benchmarkdbuser:benchmarkdbpass@DBHOSTNAME:3306/hello_world'
  9. Base = declarative_base()
  10. db_engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
  11. plugin = sqlalchemy.Plugin(db_engine, keyword='db', )
  12. app.install(plugin)
  13. class World(Base):
  14. __tablename__ = "World"
  15. id = Column(Integer, primary_key=True)
  16. randomNumber = Column(Integer)
  17. # http://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask
  18. @property
  19. def serialize(self):
  20. """Return object data in easily serializeable format"""
  21. return {
  22. 'id' : self.id,
  23. 'randomNumber': self.randomNumber
  24. }
  25. @app.route("/json")
  26. def hello():
  27. resp = {"message": "Hello, World!"}
  28. return ujson.dumps(resp)
  29. @app.route("/db")
  30. def get_random_world(db):
  31. num_queries = request.query.queries or '1'
  32. worlds = []
  33. for i in range(int(num_queries)):
  34. wid = randint(1, 10000)
  35. worlds.append(db.query(World).get(wid).serialize)
  36. return ujson.dumps(worlds)
  37. @app.route("/dbs")
  38. def get_random_world_single(db):
  39. wid = randint(1, 10000)
  40. worlds = [db.query(World).get(wid).serialize]
  41. return ujson.dumps(worlds)
  42. @app.route("/dbraw")
  43. def get_random_world_raw():
  44. connection = db_engine.connect()
  45. num_queries = request.query.queries or '1'
  46. worlds = []
  47. for i in range(int(num_queries)):
  48. wid = randint(1, 10000)
  49. result = connection.execute("SELECT * FROM world WHERE id = " + str(wid)).fetchone()
  50. worlds.append({'id': result[0], 'randomNumber': result[1]})
  51. connection.close()
  52. return ujson.dumps(worlds)
  53. @app.route("/dbsraw")
  54. def get_random_world_single_raw():
  55. connection = db_engine.connect()
  56. wid = randint(1, 10000)
  57. result = connection.execute("SELECT * FROM world WHERE id = " + str(wid)).fetchone()
  58. worlds = [{'id': result[0], 'randomNumber': result[1]}]
  59. connection.close()
  60. return ujson.dumps(worlds)
  61. if __name__ == "__main__":
  62. app.run()