Introduction to Python CGI Programming
Python CGI (Common Gateway Interface) programming is a technique that allows you to create dynamic web pages and web applications using the Python programming language. CGI is a standard protocol for web servers to execute scripts and generate dynamic content.
How Does Python CGI Work?
When a user requests a web page that requires dynamic content, the web server sends the request to the Python interpreter. The Python interpreter then executes the CGI script and generates the dynamic content, which is sent back to the web server and finally displayed to the user.
Examples of Python CGI Programming
Here are a few examples to demonstrate the use of Python CGI programming:
Example 1: Hello World
Let’s start with a simple “Hello World” example. Create a new file called “hello.py” and add the following code:
“`
#!/usr/bin/python
print(“Content-type: text/html”)
print()
print(“
Hello, World!
“)
“`
Save the file and make it executable. Place it in the CGI directory of your web server. When you access the URL associated with this script, you should see the “Hello, World!” message displayed in your web browser.
Example 2: Form Handling
CGI programming is often used for handling form submissions. Create a new file called “form.py” and add the following code:
“`
#!/usr/bin/python
import cgi
form = cgi.FieldStorage()
name = form.getvalue(‘name’)
print(“Content-type: text/html”)
print()
print(“
Hello, {}!
“.format(name))
“`
Save the file and make it executable. Create an HTML form that submits data to this script:
“`
“`
When the form is submitted, the script will retrieve the value of the “name” field and display a personalized greeting.
Example 3: Database Interaction
Python CGI programming can also be used to interact with databases. Here’s an example that demonstrates how to retrieve data from a MySQL database:
“`
#!/usr/bin/python
import cgi
import mysql.connector
form = cgi.FieldStorage()
name = form.getvalue(‘name’)
# Connect to the database
cnx = mysql.connector.connect(user=’username’, password=’password’, host=’localhost’, database=’database_name’)
cursor = cnx.cursor()
# Execute a query
query = “SELECT * FROM users WHERE name = %s”
cursor.execute(query, (name,))
# Fetch the results
results = cursor.fetchall()
print(“Content-type: text/html”)
print()
print(“
Results:
“)
for row in results:
print(“
{}
“.format(row))
# Close the database connection
cursor.close()
cnx.close()
“`
In this example, the script retrieves the value of the “name” field from the form and uses it to query a MySQL database. The results are then displayed on the web page.
Conclusion
Python CGI programming is a powerful tool for creating dynamic web pages and web applications. It allows you to interact with the web server, handle form submissions, and even interact with databases. With the examples provided, you can start exploring the possibilities of Python CGI programming and create your own dynamic web applications.