Okay, see below. The first thing I found is that it is much faster to encapsulate multiple variables inside a delimited spark variable. (; is the delimiter in my case) This allows the algorithm to call one spark variable and get all the data it needs versus having to make multiple separate REST queries. (The last version made 4 separate REST calls.) In testing, this increased performance by about 50%. Naturally, your mileage will vary and it will depend on your code.
Finally, I am no Python/Flask expert and so there is probably lots of room for further code improvement. I am open to any suggestions.
Others here have suggested that a better way to do this is using Javascript for dynamic page updates which I agree with, but I have not gotten around to re-working the code. As it stands, a page refresh is required to update the data.
Without further ado, here you go.
The base code:
from flask import Flask, render_template, request, url_for, redirect, session
import sparkfunction
app = Flask(__name__)
@app.route('/')
def DataNow():
dataDict = sparkfunction.VarUpdate("delimOT")
dataVals = dataDict.split(";")
tempdata = dataVals[0]
ledstatus = ledsparkvar(int(dataVals[1]))
utimedata = dataVals[2] + " Days, " + dataVals[3]+":" + dataVals[4] + ":" + dataVals[5]
authcookie = False
if 'authuser' in session:
authcookie = True
if (request.args.get('auth') == 'xxx') or (authcookie):
authbool = True
else:
authbool = False
return render_template('sparktemplate.html', tempdata=tempdata, utimedata=utimedata, ledstatus=ledstatus, authbool=authbool)
@app.route('/led', methods=['POST'])
def LEDChange():
sparkfunction.sparkLED(request.form['LED'])
session['authuser'] = 'xxx'
session.permanent = True
return redirect('./')
def ledsparkvar(ledstatusInt):
if ledstatusInt == 1:
ledstatus = "On"
elif ledstatusInt == 0:
ledstatus = "Off"
else:
ledstatus = "LED Error"
return ledstatus
Spark access is encapsulated in a function:
import json, requests, ssl, sys
devID = "xxxx"
AToken = "yyyy"
def VarUpdate ( varName):
spark_url = "https://api.spark.io/v1/devices/%s/%s?access_token=%s" % (devID,varName,AToken)
r = requests.get(spark_url)
data = r.json()
jsonData = "result"
OutputData = data[jsonData]
return OutputData
def sparkLED(appName):
spark_url = "https://api.spark.io/v1/devices/%s/%s" % (devID,appName)
payload = {'access_token':AToken}
r = requests.post(spark_url, params=payload)
data = r.json()
jsonData = "return_value"
return