Python CGI script with lighttpd

1.Edit lighttpd.conf

$sudo vim /etc/lighttpd/lighttpd.conf

1. Change
cgi.assign = (".php" => "/usr/bin/php5-cgi")
server.error-handler-404 = "/index.html"

To
cgi.assign = (".php" => "/usr/bin/php5-cgi",
              ".py"  => "/usr/bin/python"
	     )
server.error-handler-404 = "/index.html"

2. Change
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi")
	
To
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".py")
	
3. Change
index-file.names            = ( "index.php", "index.html", "index.lighttpd.html" )
	
To
index-file.names            = ( "index.php", "index.html", "index.lighttpd.html","index.py" )

4. sudo /etc/init.d/lighttpd force-reload

2. Testing CGI Script

1. In dictionary /var/www/cgi
sudo vim hellopy.py
	
print "Content-Type: text/html"
print
print "CGI script output"
print "

This is my first CGI script

" print "Hello, world!" 2. Access http://your_IP_address/cgi/hellopy.py You will see following content: This is my first CGI script Hello, world!

3. CGI script with root privileges

$ sudo visudo

then add the following line at the end of file :
www-data ALL=(ALL) NOPASSWD: ALL

Note: This configuration may lead to security problem. This configuration is okay for debug, but not suitable for daily use.

A better way to configure CGI script with root privileges

4. Testing CGI Script with root privileges

import os
tmp = os.popen("sudo /opt/vc/bin/vcgencmd measure_temp | grep -o '[0-9.]*'").readlines()
tmp_num=float(tmp[0])
print "Content-Type: text/html"
print "%f" %tmp_num

This CGI script will return the temperature of the CPU on the Raspberry Pi.
CGIwithRoot
Note: vcgencmd command document