Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

because you must format the output of your Python program so that the web client thinks it’s coming
from a webpage document.


To format the output of your Python program for a browser to process, you need to add a
Multipurpose Internet Mail Extensions (MIME) heading at the start of your output. You do this with
the Content-Type header, as shown here:


Click here to view code image


print('Content-Type: text/html')
print('')

After you identify the output as an HTML document, you also need to have a blank line before any
other output from the program.


Try It Yourself: Creating a Python Web Program
Now you’re ready to write a test Python program to run on the web server. Follow
along with these steps to get things going:


  1. Create a file called script2202.cgi in the folder for this hour.

  2. Open the script2202.cgi file and enter the code shown here:
    Click here to view code image
    #!/usr/bin/python3
    import math
    radius = 5
    area = math.pi radius radius
    print('Content-Type: text/html')
    print('')
    print('The area of a circle with radius', radius, 'is', area)

  3. Save the file and exit the editor.

  4. Test your script from the Python command prompt interpreter, like this:
    Click here to view code image
    pi@raspberrypi ~ $ python3 script2202.cgi
    Content-Type: text/html


The area of a circle with radius 5 is 78.53981633974483
pi@raspberrypi ~ $


  1. If this works, copy the script file to the /usr/lib/cgi-bin folder for
    publishing and make sure web clients can run it by giving everyone execute
    permissions on the file, like this:
    Click here to view code image
    pi@raspberrypi ~ $ sudo cp script2202.cgi /usr/lib/cgi-bin
    pi@raspberrypi ~ $ sudo chmod +x /usr/lib/cgi-bin/script2202.cgi
    pi@raspberrypi ~ $

  2. Open your browser and browse to the new program. Because the file is in the cgi-
    bin folder, you need to include that in the URL:
    Click here to view code image

Free download pdf