program!
Working with Dynamic Webpages
Python scripting allows you to create dynamic webpages. Dynamic webpages have the ability to
change webpage content, based on some external event, such as updating data in a database.
In Hour 21, “Using Databases in Your Programming,” you learned how to store and retrieve data
from your Python scripts by using both the MySQL and PostgreSQL database servers running on your
Raspberry Pi. You can now combine that knowledge with your CGI knowledge to create dynamic
webpages to publish database data directly on your network.
In the following Try It Yourself, you’ll write a script that can read the employees table you created
in Hour 21 and display the information on a webpage.
Try It Yourself: Publishing Database Data on the Web
The key to dynamic webpages is the ability to work with a behind-the-scenes database
to store and manipulate data. In the following steps, you’ll use the MySQL database
server and the pytest database created in Hour 21 to provide dynamic data for your
Python web application. Just follow these steps:
- Create the file script2204.cgi in this hour’s working folder.
- Open the script2204.cgi file and enter the code shown here:
Click here to view code image
1: #!/usr/bin/python3
2:
3: import mysql.connector
4: print('''Content-Type: text/html
5:
6: <!DOCTYPE html>
7:
8:
9:Dynamic Python Webpage Test
10:
11:
12:Employee Table
13:
')
14: ''')EmpID Last Name First
NameSalary
15:
16: conn = mysql.connector.connect(user='test', password='test',
database='pytest')
17: cursor = conn.cursor()
18:
19: query = ('SELECT empid, lastname, firstname, salary FROM employees')
20: cursor.execute(query)
21: for (empid, lastname, firstname, salary) in cursor:
22: print(' ')', empid, ' ')
23: print('', lastname, ' ')
24: print('', firstname, ' ')
25: print('', salary, '
26: print('
27: print('')
28: print('')
29: cursor.close()