Advertisement
Guest User

Untitled

a guest
Jul 7th, 2015
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. import argparse
  2. import sqlite3
  3. from uuid import UUID
  4.  
  5. from flask import g, json, Flask
  6.  
  7. from blocks.config import config
  8. from blocks.log.sqlite import ANCESTORS_QUERY
  9.  
  10. app = Flask(__name__)
  11.  
  12.  
  13. @app.route('/experiments', methods=['GET'])
  14. def experiments():
  15. """List the experiments"""
  16. experiments = get_db().execute(
  17. # NOT IN returns NULL if *any* value in the subquery is NULL
  18. """SELECT DISTINCT uuid FROM status WHERE uuid NOT IN (
  19. SELECT value FROM status WHERE (
  20. key = 'resumed_from' AND value IS NOT NULL
  21. )
  22. )""").fetchall()
  23. return json.jsonify({
  24. 'experiments': [UUID(bytes=bytes(e[0])) for e in experiments]
  25. })
  26.  
  27.  
  28. @app.route('/experiments/<uuid>', methods=['get'])
  29. def experiment_uuid(uuid):
  30. """Get the status of an experiment, and a list of all channels."""
  31. b_uuid = sqlite3.Binary(UUID(uuid).bytes)
  32. status = get_db().execute("SELECT key, value FROM status WHERE uuid = ?",
  33. (b_uuid,)).fetchall()
  34. entries = get_db().execute(
  35. ANCESTORS_QUERY +
  36. "SELECT DISTINCT key FROM entries WHERE uuid IN ancestors", (b_uuid,)
  37. ).fetchall()
  38. return json.jsonify({
  39. 'status': {row[0]: row[1] for row in status
  40. if not isinstance(row[1], (sqlite3.Binary, bytes))},
  41. 'entries': [row[0] for row in entries]
  42. })
  43.  
  44.  
  45. @app.route('/experiments/<uuid>/<key>', methods=['get'])
  46. def experiment_uuid_key(uuid, key):
  47. """Get the values of a channel."""
  48. b_uuid = sqlite3.Binary(UUID(uuid).bytes)
  49. # TODO Confirm whether this sort works across platforms
  50. entries = get_db().execute(
  51. ANCESTORS_QUERY + "SELECT time, MIN(value) FROM entries "
  52. "JOIN ancestors ON entries.uuid = ancestors.parent "
  53. "WHERE uuid IN ancestors AND key = ? GROUP BY time",
  54. (b_uuid, key)
  55. ).fetchall()
  56. iterations_done, values = zip(*entries)
  57. return json.jsonify({
  58. 'iterations_done': iterations_done,
  59. key: values
  60. })
  61.  
  62.  
  63. def get_db():
  64. db = getattr(g, '_database', None)
  65. if db is None:
  66. db = sqlite3.connect(args.log)
  67. return db
  68.  
  69.  
  70. @app.teardown_appcontext
  71. def close_connection(exception):
  72. db = getattr(g, '_database', None)
  73. if db is not None:
  74. db.close()
  75.  
  76. if __name__ == "__main__":
  77. parser = argparse.ArgumentParser(description='Interface for Blocks log.')
  78. parser.add_argument('log', nargs='?', type=str, help='The log to load.',
  79. default=config.sqlite_database)
  80. args = parser.parse_args()
  81. app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement