Search code examples
pythonpython-3.xflaskvirtualenvsudo

How to use a python package with sudo privileges inside Flask?


I have a Flask setup in my Raspberry Pi 4 Model B via this tutorial.

OS = Ubuntu Server 20.04.2 LTS
Python = 3.8

Please keep in mind that I am using virtual env for my Flask application as shown in the tutorial and my Flask application is running absolutely fine.

Now I installed Adafruit_DHT in the same venv and tried using the following code in one of the endpoints

import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 24)

to which I am getting the following error

File "/usr/local/lib/python3.8/dist-packages/Adafruit_DHT/common.py", line 81, in read
    return platform.read(sensor, pin)
  File "/usr/local/lib/python3.8/dist-packages/Adafruit_DHT/Raspberry_Pi_2.py", line 34, in read
    raise RuntimeError('Error accessing GPIO.')
RuntimeError: Error accessing GPIO.

So, after that, I created a simple python script say z.py and wrote the above code in it. Then, I activated the same Flask venv using

source venv1/bin/activate

And run the script using

python z.py

Again I got the same error. But If I run the above command as sudo

sudo python z.py

then script executed perfectly fine and I got the following response

87.0999984741211 29.399999618530273

So, now the question arrives, how do I use Adafruit_DHT package inside the Flask app with sudo permission?

I don't think setting 777 to www-data group would be the right choice. Or running the Flask app as sudo user would be a great idea.

I have tried installing Adafruit_DHT package globally with sudo, but still I have to execute z.py as sudo

So what is the correct way to do this?


Solution

  • I believe the package will be trying to access the device /dev/gpiomem (possibly (/dev/gpiochip0 or /dev/gpiochip1).

    I think the neatest way to address this would be have those devices be owned by a group other than root and give that group permission to access the device, e.g.

    sudo su
    groupadd gpio
    chgrp gpio /dev/gpio*
    chmod g+rw /dev/gpio*
    

    Then I'd go ahead and add your user to that group (by default this is ubuntu, but you may have created another user):

    usermod -a -G gpio ubuntu
    

    Now you've created a group called "gpio" that now has permissions to access your Pi's GPIO, and added your user to that group.

    Please note, I have not tested this