Raspberry Pi 3 – Day 8
Install Apache2 server
sudo apt-get install apache2
CGI scripts are usually stored in /usr/lib/cgi-bin, and they must have executable permission. Scripts execute when they are requested by a browser. Anything printed to stdout will be displayed in a browser, so many scripts are used to generate HTML.
sudo leafpad /etc/apache2/sites-enabled/000-default.conf & sudo a2dismod mpm_event sudo a2enmod mpm_prefork cgi
<Directory /var/www/html>
Options +ExecCGI
DirectoryIndex index.py
</Directory>
AddHandler cgi-script .py
sudo chown root.gpio /dev/mem && sudo chmod g+rw /dev/mem
sudo adduser www-data gpio
In a terminal window, type this command to reload Apache’s configuration files:
sudo service apache2 restart
sudo mv ~/Downloads/*.cgi /var/www/html cd /var/www/html && rename 's/cgi/py/g' *.py
sudo chmod +x /usr/lib/cgi-bin/*.cgi
Hello CGI
http://192.168.0.232/cgi-bin/hello.cgi
#!/usr/bin/env python print "Content-type: text/html\n\n" print "<h1>Hello World</h1>"
Passing Parameters in Raspberry Using CGI
http://192.168.0.232/test8.py?name=amar&company=woir&city=hyderabad
#!/usr/bin/env python import os # print header print "Content-type: text/html\n\n" query_string=os.environ["QUERY_STRING"] print "<h2>Query string</h2>" print "query_string: "+query_string+"<br>" print "<h2>Argument list</h2>" arg_list=query_string.split('&') #print arg_list i=1 for arg in arg_list: key, value=arg.split('=') print "key "+str(i)+": "+key+"<br>" print"value "+str(i)+": "+value+"<br>" i +=1
Passing Parameters in Raspberry Using CGI modules
http://192.168.0.232/test81.py?os=amar&cpu=woir&server=hyderabad
#!/usr/bin/env python import cgi # print header print "Content-type: text/html\n\n" print "<h2>Arguments</h2>" form = cgi.FieldStorage() arg1 = form.getvalue('os') print "OS: " +arg1+"<br>" arg2 = form.getvalue('cpu') print "CPU: "+arg2+"<br>" arg3 = form.getvalue('server') print "Server: "+arg3+"<br>"
Controlling the pin Remotely
http://192.168.0.232/test82.py?count=9
import cgi import RPi.GPIO as GPIO import time import sys # print header print "Content-type: text/html\n\n" print "<h2>Arguments</h2>" form = cgi.FieldStorage() count = form.getvalue('count') print "Your request to blink the LED at pin 12 is received - Count: "+count+"<br>" pin=12 if not str(count).isdigit(): print "Your request does not make sense - choose the correct value and try again" sys.exit() if int(count) < 1: print "Your request does not make sense - choose the correct value and try again" sys.exit() if int(count) > 10: print "We can not effort to run so many times - choose value in between 1 to 10" sys.exit() def blink(pin, state): GPIO.output(pin,state) return GPIO.setmode(GPIO.BOARD) GPIO.setup(pin,GPIO.OUT) for i in range(0, int(count)): blink(pin,GPIO.HIGH) time.sleep(0.2) blink(pin,GPIO.LOW) time.sleep(0.2) GPIO.cleanup()
Downloads
Download - Archive