杰瑞科技汇

Python CGI中getvalue如何获取表单数据?

Of course! Let's break down how to use cgi.getvalue() in Python, which is a fundamental method for handling form data in Common Gateway Interface (CGI) scripts.

Python CGI中getvalue如何获取表单数据?-图1
(图片来源网络,侵删)

What is cgi.getvalue()?

In a Python CGI script, cgi.getvalue() is the standard way to retrieve the value of a form field that was submitted from an HTML page (usually via the GET or POST method).

  • CGI (Common Gateway Interface): A standard protocol for web servers to execute programs (like Python scripts) and exchange data with them.
  • cgi module: Python's built-in library for creating CGI scripts.
  • form.getvalue('field_name'): This method looks for a form field with the name 'field_name' and returns its value.

How it Works: The Core Concept

When a user fills out and submits a form, the browser sends the data to the server. The server then executes your Python CGI script, passing the form data to it. The cgi module parses this data and makes it available to your script in a special object called form.

cgi.getvalue() is a method on this form object.


Step-by-Step Example: A Simple Form and CGI Script

Let's create a complete, runnable example.

Python CGI中getvalue如何获取表单数据?-图2
(图片来源网络,侵删)

Step 1: Create the HTML Form (index.html)

This form will send data using the GET method. The action points to our Python script.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">CGI Form Example</title>
</head>
<body>
    <h1>Enter Your Information</h1>
    <form action="/cgi-bin/process_form.py" method="GET">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br><br>
        <label for="favorite_color">Favorite Color:</label><br>
        <select id="favorite_color" name="favorite_color">
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
        </select><br><br>
        <label>
            <input type="checkbox" name="subscribe" value="yes"> Subscribe to newsletter
        </label><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Key Points:

  • action="/cgi-bin/process_form.py": This tells the server to execute the Python script located at /cgi-bin/process_form.py. Your server must be configured to run Python scripts in the cgi-bin directory.
  • method="GET": The form data will be appended to the URL in the browser's address bar (e.g., .../process_form.py?username=John&favorite_color=blue&subscribe=yes).
  • name="...": The name attribute of each input field is crucial. This is the key you'll use in your Python script to get the value.

Step 2: Create the Python CGI Script (process_form.py)

This script will be placed in your server's cgi-bin directory.

#!/usr/bin/env python3
import cgi
import html
# --- 1. Setup CGI Header ---
# This must be the very first thing printed to stdout.
# It tells the browser what kind of content to expect.
print("Content-Type: text/html\n\n")
# --- 2. Create a Form Object ---
# The cgi.FieldStorage() object parses the form data.
# It's the 'form' object we will call .getvalue() on.
form = cgi.FieldStorage()
# --- 3. Get Values Using getvalue() ---
# Get a single value from a text field
# .getvalue() returns None if the field doesn't exist.
username = form.getvalue('username')
# Get a value from a dropdown menu
color = form.getvalue('favorite_color')
# Get a value from a checkbox
# Note: A checkbox is only sent if it's checked.
subscribe = form.getvalue('subscribe')
# --- 4. Display the Results ---
# Use html.escape() to prevent Cross-Site Scripting (XSS) attacks.
# This is a critical security practice!
print("<html>")
print("<head><title>Form Results</title></head>")
print("<body>")
print("<h1>Thank You!</h1>")
print("<p>Here is the information you submitted:</p>")
if username:
    print(f"<p><strong>Username:</strong> {html.escape(username)}</p>")
else:
    print("<p><strong>Username:</strong> Not provided.</p>")
if color:
    print(f"<p><strong>Favorite Color:</strong> {html.escape(color)}</p>")
else:
    print("<p><strong>Favorite Color:</strong> Not selected.</p>")
if subscribe:
    print(f"<p><strong>Newsletter:</strong> Yes, please subscribe me!</p>")
else:
    print("<p><strong>Newsletter:</strong> No, thank you.</p>")
print("</body>")
print("</html>")

Detailed Explanation of cgi.getvalue()

Handling Missing Fields

If a user doesn't fill in a field, form.getvalue('field_name') will return None. This is why we use if username: in the example. This is more Pythonic than checking if username is not None:.

Python CGI中getvalue如何获取表单数据?-图3
(图片来源网络,侵删)
# Safe way to get a value with a default
# If 'username' is not in the form, it will return 'Guest'
username = form.getvalue('username', 'Guest')
# Another way to check
username = form.getvalue('username')
if not username:
    username = "Guest"

Handling Multiple Values (e.g., Checkboxes or Multi-Select)

If you have multiple form fields with the same name (like a group of checkboxes), form.getvalue() will only return the first value it finds.

To get all values, you must use form.getlist('field_name'). This returns a list of strings.

Example HTML:

<input type="checkbox" name="hobby" value="reading"> Reading
<input type="checkbox" name="hobby" value="sports"> Sports
<input type="checkbox" name="hobby" value="music"> Music

Example Python:

import cgi
import html
print("Content-Type: text/html\n\n")
form = cgi.FieldStorage()
# Use getlist() to get all values for the 'hobby' field
hobbies = form.getlist('hobby')
print("<h2>Your Hobbies:</h2>")
if hobbies:
    for hobby in hobbies:
        print(f"<p>{html.escape(hobby)}</p>")
else:
    print("<p>You didn't select any hobbies.</p>")

Handling GET vs. POST

  • GET: Data is sent in the URL. Good for non-sensitive data and bookmarks. You can see the data in the address bar.
  • POST: Data is sent in the body of the HTTP request. Better for sensitive data (passwords) and large amounts of data.

The beauty of the cgi module is that you don't need to change your Python code. Whether the form uses method="GET" or method="POST", cgi.FieldStorage() handles the parsing correctly. Your script using getvalue() will work in both cases.


Important Considerations

  1. Security: html.escape() As shown in the example, always use html.escape() on any user-supplied data before printing it to an HTML page. This prevents Cross-Site Scripting (XSS) attacks, where a malicious user could inject harmful JavaScript code into your page.

  2. Server Configuration For this to work, your web server (like Apache or Nginx) must be configured to:

    • Recognize the /cgi-bin/ directory.
    • Treat .py files as executable CGI scripts.
    • Have the correct permissions (usually 755 for the script, 755 for the cgi-bin directory, and 644 for HTML files).
  3. Modern Alternatives While CGI is a great learning tool, it's largely considered outdated for production web development. Modern Python web frameworks like Flask and Django are much more powerful, secure, and easier to use. They handle routing, templating, and security for you, so you don't have to manually print headers or escape HTML.

    For example, the same form submission in Flask would look like this:

    # app.py
    from flask import Flask, request, render_template
    app = Flask(__name__)
    @app.route('/process', methods=['GET', 'POST'])
    def process_form():
        if request.method == 'POST':
            username = request.form.get('username')
            color = request.form.get('favorite_color')
            subscribe = request.form.get('subscribe')
            # ... process data ...
            return f"Username: {username}, Color: {color}"
        return render_template('index.html') # Shows the form
分享:
扫描分享到社交APP
上一篇
下一篇