'How do I run a Flask-Application with GPIO-Usage in Apache?

I have a Flask app which runs on a Raspberry Pi and uses GPIO to control a led-strip:

strip = Adafruit_NeoPixel(10, 18, 800000, 10, 255, False, 0)

app = Flask(__name__)

@app.route('/light', methods={'GET'})
def index():
    strip.setPixelColor(0, Color(255, 255, 255))
    return 'light'


strip.begin()

app.run(host="0.0.0.0", port="8080")

Also there is this app.wsgi file to enable apache so serve the application:

#!/usr/bin/env python3

# if using venv
activate_this = '/var/www/application/venv/bin/activate_this.py'
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this))

import sys
sys.path.insert(0, '/var/www/application')

from app import app as application

And finally a app.conf file to configure the VirtualHost:

<VirtualHost *:80>
        ServerName app
        WSGIDaemonProcess app user=pi group=www-data threads=5
        WSGIScriptAlias / /var/www/application/app.wsgi

        <Directory /var/www/app>
                WSGIProcessGroup app
                WSGIApplicationGroup &{GLOBAL}
                Require all granted

                DirectoryIndex disabled
        </Directory>
</VirtualHost>

I am also using venv for the python dependencies.

Now, the problem is, that I need to run this app with root, because gpio requires it.

This is fine for testing, but apache doesn't run it with root permission and therefore fails.

  • Configuring apache to run this as root will be prevented and results in errors

  • Setting the SUID bit for app.py and changing the ownership to root is not working for non-binaries in unix shells https://unix.stackexchange.com/a/130910

  • Then I found out that I am currently using PWM for the led control and with SPI I would be able to run the app without sudo when my user is in the gpio group. However, this resulted in weird led behaviour and I can't find any information on how to address this problem.

How can I further approach this problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source