Reputation: 1219
I am trying to get my very first Flask App running. I'm still trying to get the right structure of the code right.
At first load of the website I need to run two initial commands:
/usr/local/bin/gpio -g mode 23 out
/usr/local/bin/gpio -g mode 20 out
I guess I would put that just right above the @app.route part.
Then, I would like to have a couple of buttons on the website. Those buttons are supposed to execute simple commands when clicked or to run the code that is currently written in a python script.
So the Up command is:
/usr/local/bin/gpio -g write 23 0
/usr/local/bin/gpio -g write 20 1
The Down command is:
/usr/local/bin/gpio -g write 23 1
/usr/local/bin/gpio -g write 20 0
The Stop command is:
/usr/local/bin/gpio -g write 23 1
/usr/local/bin/gpio -g write 20 1
The LED on button is supposed to run a whole python script full of code. As currently it is a python script, I try to run that script (similar to this "Full example code")after the button has been clicked. This script runs in an animation loop as soon as it gets executed.
The LED off button runs a command in order to kill that script.
sudo pkill -f ws281x.py
As if that is not enough to handle, I have two more python scripts that are supposed to run an OLED screen and a DHT11 sensor. Thos two are supposed to run in the background as soon as the website gets called for the first time (no button pressing).
My main question is, what would be the best practice in flask to get all of this together? With the following Sub-Questions:
I dont want you to write the code for me. I just need to get the right idea of how to structure all of this, as it is quite some code to handle.
Upvotes: 0
Views: 264
Reputation: 24966
By "At first load of the website" do you mean when the web server starts, or when the first request is made?
If the former, then making those gpio requests before you create the instance of Flask
should work. If the latter, for the moment, you can use the deprecated before_first_request decorator.
A route for each button is a reasonable way to structure the code.
For continuously sampling a sensor, you can spawn a thread before the application starts, and, with some appropriate locking, update some global data structure (e.g., a dict) that routes can pull data from. E.g., if lock
is a threading.Lock()
, then the thread would do
with lock:
shared['temp'] = read_dht11()
and the route would do
with lock:
temp = shared['temp']
Upvotes: 1