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

(singke) #1
http://localhost/cgi-bin/script2202.py
You should see the results of your program appear in your web browser, as shown in
Figure 22.2!

FIGURE 22.2 The results of the script2202.cgi file in the browser.

Congratulations! You’ve run your Python program on the Web! However, this is pretty boring, as
webpages go. In the next section, you’ll take a look at how to spice up your Python webpages a bit.


Expanding Your Python Webpages


Now that you’ve seen the basics of how to get your Python programs to run on the Web, you can dive
a little deeper into the process. In the following sections, you’ll first learn how to format your
program code so that it appears more like a real webpage instead of just program output. Then you’ll
look at how to make your Python webpages more dynamic by enabling them to access database data
and display it on the webpage. Finally, you’ll add some debugging features to your code in case
things go wrong.


Formatting Output


You may have noticed from the example in Figure 22.2 that just displaying the output from your
Python code directly to the web browser isn’t all that exciting. Browsers were created to display
formatted text, using Hypertext Markup Language (HTML). HTML enables you to use plan-text
commands to identify formatting features such as layouts, fonts, and colors. Because all the HTML
coding is done in text, you can output that from your Python programs and pass it to the client
browser.


All you need to do is add some HTML code to your Python output to help liven things up a bit. Listing
22.1 shows the script2203.cgi program, which embeds HTML code inside the Python script to

Free download pdf