Saturday, May 16, 2020

Running python cgi scripts on the Raspberry Pi nginx

Basically, the setup of python plugin cgi is here at https://www.takaitra.com/running-python-cgi-scripts-on-the-raspberry-pi/
and the enhanced functions of uwsgi-cgi documentation here https://uwsgi-docs.readthedocs.io/en/latest/CGI.html
Except the followings:

# Build and install the uwsgi with the cgi plugin
wget https://projects.unbit.it/downloads/uwsgi-latest.tar.gz
tar zxvf uwsgi-latest.tar.gz 
cd uwsgi-2.0.18
# compile as cgi plugin
make PROFILE=cgi
sudo cp uwsgi /usr/local/bin/



# Create the file /etc/uwsgi.ini
plugins = cgi
# change to unix sock
socket = /tmp/uwsgi.sock
#socket = 127.0.0.1:9000
module = pyindex
cgi = /var/www/html/cgi-bin
#cgi = /usr/share/nginx/www
cgi-allowed-ext = .py
cgi-helper = .py=python
logger=file:/tmp/uwsgi-error.log
uid = www-data
gid = www-data



# Add a location to the /etc/nginx/sites-available/default
location ~ \.py$ {
  # uwsgi_pass 127.0.0.1:9000;
  # change to unix sock
  uwsgi_pass unix:/tmp/uwsgi.sock;
  include uwsgi_params;
  uwsgi_modifier1 9;
}


Test this python script to show the temperature of Raspberry Pi in a html web page

/var/www/html/cgi-bin/temp.py    Select all
#!/usr/bin/env python import os # Return CPU temperature as a character string def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) #We have to print a valid HTTP header first so the browser will know how to decode the data print "Content-type: text/html\n\n" temp1=getCPUtemperature() print temp1


/var/www/html/temp.html    Select all
<html> <head> <title>Pi Temp</title> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> </head> <body> <h1>Temp from Pi</h1> <script> $(document).ready(function () { var interval = 500; //number of milli seconds between each call var refresh = function() { $.ajax({ url: "temp.py", cache: false, success: function(html) { $('#pi-temp-here').html(html); setTimeout(function() { refresh(); }, interval); } }); }; refresh(); }); </script> <div id="pi-temp-here"></div> </body> </html>


// sed 's/<\([^>]*\)>/\<\1\>/g;'


Shell script    Select all
# Append video Group to www-date user sudo usermod -aG video www-data # reboot the Raspberry Pi and test the python cgi script sudo reboot http://127.0.0.1/temp.html




To install FastCGI for php in ngnix, please follow this guide -> https://getgrav.org/blog/raspberrypi-nginx-php7-dev

If you use buster, it will install the latest php-7.3, so change everything from 7.2 from this guide to 7.3 and the installation of packages will be
sudo apt-get update
sudo apt-get install php php-curl php-gd php-fpm php-cli php-opcache php-mbstring php-xml php-zip


#add in /etc/php/7.3/fpm/pool.d/www.conf
user = pi
group = pi


#reload web server and test
#check to ensure the /var/run/php/php7.3-fpm.sock file exists
sudo service nginx restart
sudo service php7.3-fpm restart




No comments: