Commit f1521e96 authored by Jérome Perrin's avatar Jérome Perrin

platform: remove unused code on server side

parent 6bf6f3ba
import json
import subprocess
from pprint import pformat
from flask import Flask, jsonify, redirect, url_for
from flask import request
app = Flask(__name__)
from dream.simulation.LineGenerationJSON import main as simulate_line_json
global data
data = {'model': None,
'simulation_parameters': {}}
app = Flask(__name__)
@app.route("/")
def welcome():
app.logger.debug('welcome')
def front_page():
return redirect(url_for('static', filename='index.html'))
@app.route("/addModel")
def addModel():
pass
def main(*args):
app.run(debug=True)
@app.route("/someTest", methods=["POST", "OPTIONS"])
def someTest():
app.logger.debug('someTest')
app.logger.debug(request)
app.logger.debug(request.__dict__)
app.logger.debug("request headers content type: %r" % (request.headers['Content-Type'],))
app.logger.debug("request.json: %r" % (request.json,))
response =request.json
return jsonify(request.json)
@app.route("/setModel", methods=["POST", "OPTIONS"])
def setModel():
app.logger.debug('setModel')
data['model'] = request.json
data['simulation_parameters'] = {}
app.logger.debug("model: %r" % (data['model'],))
return "ok"
@app.route("/updateModel", methods=["POST", "OPTIONS"])
def updateModel():
app.logger.debug('updateModel')
data['model'] = request.json
return "ok"
@app.route("/setSimulationParameters", methods=["POST", "OPTIONS"])
def setSimulationParameters():
app.logger.debug('setSimulationParameters')
parameter_dict = request.json
app.logger.debug("parameter_dict: %r" % (parameter_dict,))
data['simulation_parameters']['available_people'] = parameter_dict
return "ok"
def _simulate():
# Well, it's only dummy code now, but we will have to think about
# running simulation later
box_to_enable_list = [1, 2, 3, 7, 8, 9]
people_dict = data['simulation_parameters'].get('available_people', {})
available_people_list = [x for x in people_dict if people_dict[x]]
to_enable = len(available_people_list) >= 6
throughput = None
for box in data['model']["box_list"]:
box["worker"] = None
box["enabled"] = False
if int(box["id"][len("window"):]) in box_to_enable_list:
box["enabled"] = to_enable
if to_enable:
box["worker"] = available_people_list.pop()
if throughput is None:
throughput = box["throughput"]
throughput = min(throughput, box["throughput"])
app.logger.debug('box and throughput : %r, %r' % (box, throughput))
if throughput is None:
throughput = 0
data['model']["throughput"] = throughput
@app.route("/getModel", methods=["GET", "OPTIONS"])
def getModel():
app.logger.debug('getModel')
_simulate()
return jsonify(data['model'])
@app.route("/runSimulation", methods=["POST", "OPTIONS"])
def runSimulation():
parameter_dict = request.json['json']
app.logger.debug("running with:\n%s" % (pformat(parameter_dict,)))
if 0:
p = subprocess.Popen(['./bin/dream_simulation', '-', '-'], shell=True, bufsize=8192,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
p.stdin.write(json.dumps(parameter_dict))
app.logger.debug(p.stdout.read())
from dream.simulation.LineGenerationJSON import main
return jsonify(json.loads(main(input_data=json.dumps(parameter_dict))))
return jsonify(json.loads(simulate_line_json(input_data=json.dumps(parameter_dict))))
def main(*args):
app.run(debug=True)
if __name__ == "__main__":
main()
# This code comes from http://flask.pocoo.org/snippets/56/
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
# XXX It should not be necessary to hardcode allow-headers
h['Access-Control-Allow-Headers'] = 'Content-Type'
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
def deunicodeData(data):
if isinstance(data, list):
new_data = []
for sub_data in data:
new_data.append(deunicodeData(sub_data))
elif isinstance(data, unicode):
new_data = data.encode('utf8')
elif isinstance(data, dict):
new_data = {}
for key, value in data.iteritems():
key = deunicodeData(key)
value = deunicodeData(value)
new_data[key] = value
elif isinstance(data, (int, float)):
new_data = data
else:
raise ValueError("unknow type : %r" % (data,))
return new_data
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment