app.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. from bottle import Bottle, route, request, run, template, response
  2. from bottle.ext import sqlalchemy
  3. from sqlalchemy import create_engine, Column, Integer, Unicode
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from random import randint
  6. import sys
  7. from operator import attrgetter, itemgetter
  8. from functools import partial
  9. try:
  10. import ujson as json
  11. except ImportError:
  12. import json
  13. app = Bottle()
  14. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://benchmarkdbuser:benchmarkdbpass@DBHOSTNAME:3306/hello_world?charset=utf8'
  15. Base = declarative_base()
  16. db_engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
  17. plugin = sqlalchemy.Plugin(db_engine, keyword='db', )
  18. app.install(plugin)
  19. if sys.version_info[0] == 3:
  20. xrange = range
  21. class World(Base):
  22. __tablename__ = "World"
  23. id = Column(Integer, primary_key=True)
  24. randomNumber = Column(Integer)
  25. # http://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask
  26. @property
  27. def serialize(self):
  28. """Return object data in easily serializeable format"""
  29. return {
  30. 'id' : self.id,
  31. 'randomNumber': self.randomNumber
  32. }
  33. class Fortune(Base):
  34. __tablename__ = "Fortune"
  35. id = Column(Integer, primary_key=True)
  36. message = Column(Unicode)
  37. @app.route("/json")
  38. def hello():
  39. response.content_type = 'application/json'
  40. resp = {"message": "Hello, World!"}
  41. return json.dumps(resp)
  42. @app.route("/db")
  43. def get_random_world(db):
  44. num_queries = request.query.get('queries', 1, type=int)
  45. worlds = []
  46. rp = partial(randint, 1, 10000)
  47. for i in xrange(num_queries):
  48. worlds.append(db.query(World).get(rp()).serialize)
  49. response.content_type = 'application/json'
  50. return json.dumps(worlds)
  51. @app.route("/dbs")
  52. def get_random_world_single(db):
  53. wid = randint(1, 10000)
  54. world = db.query(World).get(wid).serialize
  55. response.content_type = 'application/json'
  56. return json.dumps(world)
  57. @app.route("/dbraw")
  58. def get_random_world_raw():
  59. connection = db_engine.connect()
  60. num_queries = request.query.get('queries', 1, type=int)
  61. worlds = []
  62. rp = partial(randint, 1, 10000)
  63. for i in xrange(int(num_queries)):
  64. result = connection.execute("SELECT * FROM world WHERE id = " + str(rp())).fetchone()
  65. worlds.append({'id': result[0], 'randomNumber': result[1]})
  66. connection.close()
  67. response.content_type = 'application/json'
  68. return json.dumps(worlds)
  69. @app.route("/dbsraw")
  70. def get_random_world_single_raw():
  71. connection = db_engine.connect()
  72. wid = randint(1, 10000)
  73. result = connection.execute("SELECT * FROM world WHERE id = " + str(wid)).fetchone()
  74. worlds = {'id': result[0], 'randomNumber': result[1]}
  75. connection.close()
  76. response.content_type = 'application/json'
  77. return json.dumps(worlds)
  78. @app.route("/fortune")
  79. def fortune_orm(db):
  80. fortunes=db.query(Fortune).all()
  81. fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
  82. fortunes=sorted(fortunes, key=attrgetter('message'))
  83. return template('fortune-obj', fortunes=fortunes)
  84. @app.route("/fortuneraw")
  85. def fortune_raw():
  86. connection = db_engine.connect()
  87. fortunes=[(f.id, f.message) for f in connection.execute("SELECT * FROM Fortune")]
  88. fortunes.append((0, u'Additional fortune added at request time.'))
  89. fortunes=sorted(fortunes, key=itemgetter(1))
  90. connection.close()
  91. return template('fortune', fortunes=fortunes)
  92. @app.route("/updates")
  93. def updates(db):
  94. """Test 5: Database Updates"""
  95. num_queries = request.query.get('queries', 1, type=int)
  96. if num_queries > 500:
  97. num_queries = 500
  98. worlds = []
  99. rp = partial(randint, 1, 10000)
  100. ids = [rp() for _ in xrange(num_queries)]
  101. ids.sort() # To avoid deadlock
  102. for id in ids:
  103. world = db.query(World).get(id)
  104. world.randomNumber = rp()
  105. worlds.append(world.serialize)
  106. response.content_type = 'application/json'
  107. return json.dumps(worlds)
  108. @app.route("/raw-updates")
  109. def raw_updates():
  110. """Test 5: Database Updates"""
  111. num_queries = request.query.get('queries', 1, type=int)
  112. if num_queries > 500:
  113. num_queries = 500
  114. conn = db_engine.connect()
  115. worlds = []
  116. rp = partial(randint, 1, 10000)
  117. for i in xrange(num_queries):
  118. world = conn.execute("SELECT * FROM World WHERE id=%s", (rp(),)).fetchone()
  119. randomNumber = rp()
  120. worlds.append({'id': world['id'], 'randomNumber': randomNumber})
  121. conn.execute("UPDATE World SET randomNumber=%s WHERE id=%s",
  122. (randomNumber, world['id']))
  123. conn.close()
  124. response.content_type = 'application/json'
  125. return json.dumps(worlds)
  126. @app.route('/plaintext')
  127. def plaintext():
  128. """Test 6: Plaintext"""
  129. response.content_type = 'text/plain'
  130. return b'Hello, World!'
  131. if __name__ == "__main__":
  132. app.run(host='0.0.0.0', debug=False)