I am working on a project that at its core, runs a server for a remote monitoring type website to monitor some data from a separate dashboard system on a car over LTE. The car will send its speed and temperature data to the web server through post (/API/post) the server passes it along to the /api/getval so that the javascript can grab and display the info. All of that seems to be working. The problem is that the python-flask server is throwing out zero in the /api/getval route. I know the variables should be saved correctly because it repeats the content back along with the post request, and upon setting the jsonify object to a set value, it returns that to the getval properly. Only when linking the two does it suddenly forget. I tried returning the "data" variable and it returns correctly, so I know that is getting read correctly, but yet it still returns zero. attached is the 2 python routs that handle these requests
def handle():
global speed
global temp
data = request.get_json()
speed = data['Speed']
temp = data['Temp']
return jsonify({'result' : '200', 'Speed' : speed, 'Temp' : temp})
@app.route('/api/getval')
def getdata():
return jsonify({ 'Speed' : speed, 'Temp' : temp })
The confusing part to me is not that it doesn't work, it's that it has stopped working. All code was run on a Windows laptop for development, and it has worked on that laptop flawlessly. However, everything broke when I tried to push it to a Ubuntu server hosted at my home. Nothing has been changed other than directories. The server is running through Nginx and gunicorn, but Windows development was done through the "Flask run" command. the speed and temp variables are set just after the import command and should not be setting back to 0 any other time. Thanks in advance for any help, this is probably yet again something simple that I am overlooking.
On an async server like Flask with multiple processes, you cannot use variables outside of the route to store dynamic data. Instead, you can use Redis like below:
import redis
red = redis.Redis()
red.set("hello","hi!") # set redis key "hello"
red.get("hello") # get hello from the cacher -> when you need the variable
Note: You need to setup redis-server to your host machine, if you're on Windows, you need to install the 2016 exe version because they no longer support Windows
I hope this fixes the issue