from flask import Flask, request, redirect, url_for, make_response, render_template, Markup, send_from_directory, send_file, jsonify, Response from flask_redis import FlaskRedis import json, abp, markdown from pprint import pprint import raussendorf import humanhash DAY = 60*60*24 app = Flask(__name__) redis = FlaskRedis(app) @app.route("/") def index(): secret, uuid = humanhash.uuid() return redirect("/{}".format(secret)) @app.route("/") def main(uuid): return render_template("index.html", uuid=uuid) @app.route("//graph", methods=["GET", "POST"]) def graph(uuid): if request.method == 'POST': # Convert the data to a graph state g = abp.GraphState() g.from_json(json.loads(request.data)) # Convert it back to JSON just for fun data = json.dumps(g.to_json(stringify=True)) # Insert into the database redis.setex(uuid, data, DAY) # Return success return "Posted {} bytes OK".format(len(data)) elif redis.exists(uuid): return jsonify(json.loads(redis.get(uuid))) else: g = abp.GraphState() data = g.to_json(stringify=True) redis.setex(uuid, DAY, json.dumps(data)) return jsonify(data) @app.route("//edit", methods=["POST"]) def edit(uuid): # Load the graph from the database g = abp.GraphState() g.from_json(json.loads(redis.get(uuid))) # Apply the edit to the graph edit = json.loads(request.data) action = edit["action"] pprint(edit, indent=2) if action == "create": g.add_qubit(edit["name"], position=edit["position"], vop=0) elif action == "cz": g.act_cz(edit["start"], edit["end"]) elif action == "hadamard": g.act_hadamard(edit["node"]) elif action == "phase": g.act_local_rotation(edit["node"], "phase") elif action == "delete": g._del_node(edit["node"]) elif action == "localcomplementation": g.local_complementation(edit["node"]) elif action == "measure": g.measure(edit["node"], "p"+edit["basis"]) elif action == "clear": g = abp.GraphState() elif action == "raussendorf": g = raussendorf.raussendorf() else: pass # New state into JSON and database data = json.dumps(g.to_json(stringify=True)) redis.setex(uuid, DAY, data) return data @app.route("/doc") def doc(): body = Markup(markdown.markdown(render_template("doc.md"), extensions=["markdown.extensions.codehilite"])) return render_template("boilerplate.html", body=body) @app.route("//download") def download(uuid): return Response(redis.get(uuid), mimetype='application/json', headers={'Content-Disposition':'attachment;filename=graph.json'})