added JSON capabilities to webserver

redesign
Josef Dabrowski 7 years ago
parent 35efd69424
commit 4fc0329d3f

@ -8,7 +8,7 @@
<body>
<div>
<form action="/home" method="post">
<form action="/home" class='form' method="post">
{% for n in range(widgLists| length) %}
<h4>Widget {{n}}</h4>
{% for key, value in widgLists[n].iteritems() %}
@ -24,10 +24,61 @@
<br>
{% endfor %}
<br>
<input type="submit" value="Submit">
</form>
</div>
<script>
/**
* Retrieves input data from a form and returns it as a JSON object.
* @param {HTMLFormControlsCollection} elements the form elements
* @return {Object} form data as an object literal
*/
const isValidElement = element => {
return element.name && element.value;
};
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
if (isValidElement(element)) {
data[element.name] = element.value;
}
return data;
}, {});
const handleFormSubmit = event => {
// Stop the form from submitting since were handling that with AJAX.
event.preventDefault();
// Call our function to get the form data.
const data = formToJSON(form.elements);
/**
// Demo only: print the form data onscreen as a formatted JSON object.
const dataContainer = document.getElementsByClassName('results__display')[0];
// Use `JSON.stringify()` to make the output valid, human-readable JSON.
dataContainer.textContent = JSON.stringify(data, null, " ");
// ...this is where wed actually do something with the form data...
**/
var textContent = JSON.stringify(data, null, " ");
var request = new XMLHttpRequest();
request.open('POST', '/home', true);
request.setRequestHeader('Content-Type', 'application/json');
request.send(textContent);
};
/*
* This is where things actually get started. We find the form element using
* its class name, then attach the `handleFormSubmit()` function to the
* `submit` event.
*/
const form = document.getElementsByClassName('form')[0];
form.addEventListener('submit', handleFormSubmit);
</script>
</body>
</html>

@ -9,10 +9,12 @@ mydir = os.path.dirname(os.path.abspath(__file__))
mydir = os.path.join(mydir, '../')
# print(mydir)
essentials = {'type': None, 'height': None, 'width': None, 'posX': None, 'posY': None}
essentials = {'type': None, 'height': None,
'width': None, 'posX': None, 'posY': None}
trello_options = {'board': None, 'list': None}
image_options = {'filename': None, 'scaleMode': None, 'bwStyle': None}
def convert(input):
if isinstance(input, dict):
return dict((convert(key), convert(value)) for key, value in input.iteritems())
@ -25,18 +27,25 @@ def convert(input):
# HOMEPAGE
@app.route('/home', methods=['GET', 'POST'])
def home():
def home(): # Toml config passed to html page via two dicts.
# Form data passed back to webserver as JSON.
config = read_config()
widgLists, sysList = prep_dict_for_web(config)
if request.method == 'POST':
jsonData = request.get_json()
print(jsonData)
jsonData = convert(jsonData)
# update system variables
for key in sysList:
if request.form[key]:
if isInt(request.form[key]):
print("%" + jsonData[key] + "$")
if jsonData[key]:
if isInt(jsonData[key]):
#print(request.form[key] + " is int")
sysList[key] = int(request.form[key])
sysList[key] = int(jsonData[key])
else:
sysList[key] = request.form[key]
sysList[key] = jsonData[key]
# update widget variables
# for i in range(len(widgLists)):
# for key in widgLists[i]:
@ -45,19 +54,18 @@ def home():
for i in range(len(widgLists)):
for key in widgLists[i]:
# print(request.form[key+str(i)])
if isInt(request.form[key+str(i)]):
if jsonData[key + str(i)]:
if isInt(jsonData[key + str(i)]):
#print(request.form[key+str(i)] + " is int")
widgLists[i][key] = int(request.form[key+str(i)])
widgLists[i][key] = int(jsonData[key + str(i)])
else:
widgLists[i][key] = request.form[key+str(i)]
#print(widgLists)
#print(sysList)
widgLists[i][key] = jsonData[key + str(i)]
update_config(widgLists, sysList)
return render_template('home.html', title='Overview', widgLists=widgLists, sysList=sysList)
def isInt(s):
try:
int(s)
@ -65,6 +73,7 @@ def isInt(s):
except ValueError:
return False
def prep_dict_for_web(config):
widgLists = config['widgets'] # list of dicts
sysList = {} # dict
@ -73,6 +82,7 @@ def prep_dict_for_web(config):
sysList[key] = config[key]
return widgLists, sysList
def read_config():
uni_config = toml.load(os.path.join(mydir, 'config.toml'))
config = convert(uni_config)
@ -84,6 +94,7 @@ def read_config():
# ], 'cellsHeight': 3, 'resHeight': 384, 'resWidth': 640, 'cellsWidth': 3}
return config
def update_config(widgLists, sysList):
config = {'widgets': widgLists}
for key in sysList:
@ -93,5 +104,6 @@ def update_config(widgLists, sysList):
with open(path, "w+") as config_file:
config_file.write(toml.dumps(config))
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Loading…
Cancel
Save