杰瑞科技汇

windows python cgi

Of course! Here is a comprehensive, step-by-step guide to setting up and running a Python CGI (Common Gateway Interface) script on a Windows machine.

windows python cgi-图1
(图片来源网络,侵删)

This guide will cover:

  1. Understanding CGI on Windows: How it works with IIS.
  2. Prerequisites: What you need installed.
  3. Step-by-Step Setup: Detailed instructions to configure IIS.
  4. Writing a Python CGI Script: A simple "Hello, World!" and a more advanced form handler.
  5. Running and Testing: How to see your script in action.
  6. Troubleshooting Common Issues: Solving the most frequent problems.

Understanding CGI on Windows

On Windows, the most common web server that supports CGI out-of-the-box is Internet Information Services (IIS). Unlike on Linux where you might use Apache or a simple built-in server, IIS is the standard for Windows.

The core concept is the same:

  1. A user's browser requests a URL, like http://localhost/cgi-bin/myscript.py.
  2. IIS sees the .py extension and knows it needs to execute this file using the Python interpreter.
  3. IIS sets up special "environment variables" that contain information about the request (e.g., the user's browser, the form data, etc.).
  4. IIS captures everything the Python script prints to its Standard Output.
  5. IIS sends this captured output back to the user's browser as the HTTP response.

Prerequisites

  1. Python Installed: Make sure you have Python installed on your Windows machine. You can download it from python.org. During installation, crucially, check the box that says "Add Python to PATH". This allows the command line to find python.exe.

    windows python cgi-图2
    (图片来源网络,侵删)
  2. IIS Installed: IIS is a Windows feature that you need to enable.

    • Press the Windows Key, type "Turn Windows features on or off", and press Enter.
    • In the dialog box, expand Internet Information Services.
    • Expand World Wide Web Services.
    • Expand Application Development Features.
    • Check the box for CGI.
    • Click OK. Windows will install the necessary files.

Step-by-Step IIS Configuration

Let's set up a directory for our CGI scripts and configure IIS to run them.

Step 3.1: Create a Directory for Your Scripts

It's a best practice to keep your scripts separate from your main website files.

  1. Open File Explorer.
  2. Create a new folder. A good location is C:\inetpub\wwwroot\cgi-bin.
    • C:\inetpub\wwwroot is the default root directory for IIS websites.
    • cgi-bin is a conventional name for a directory that holds executable scripts.

Step 3.2: Configure IIS to Execute Python Scripts

Now we'll tell IIS that any file in the cgi-bin folder ending in .py should be executed by Python.

windows python cgi-图3
(图片来源网络,侵删)
  1. Open Internet Information Services (IIS) Manager. You can search for it in the Start Menu.

  2. In the left pane, expand your server name, then expand Sites, and click on Default Web Site.

  3. In the Actions pane on the right, click on Add Virtual Directory....

    • Alias: cgi-bin (This is the name you'll use in the URL).
    • Physical path: Browse to the folder you created, e.g., C:\inetpub\wwwroot\cgi-bin.
    • Click OK.
  4. Now, select the new cgi-bin virtual directory in the left pane.

  5. In the center pane, double-click on Handler Mappings.

  6. In the Actions pane on the right, click Add Managed Handler....

    • Request path: *.py
    • Type: Python.CgiHandler
    • Name: PythonCGI (You can name this anything you like).
    • Click OK.
  7. Important Security Step: By default, IIS might block execution. Make sure the "Execute" permission is set.

    • Select the cgi-bin virtual directory again.
    • In the center pane, double-click on Handler Mappings.
    • Find the PythonCGI handler you just created in the list.
    • Select it and click Request Restrictions... in the Actions pane.
    • Go to the Access tab.
    • Check the box for Execute (Scripts and Executables).
    • Click OK on all the open windows.

Your IIS configuration is now complete!


Writing a Python CGI Script

CGI scripts have a special requirement: the very first line of output must be a Content-Type header, followed by a blank line. This tells the browser what kind of data to expect (e.g., HTML, plain text).

Example 1: Simple "Hello, World!" Script

  1. Open a text editor (like Notepad++, VS Code, or even Notepad).

  2. Save the following code in your C:\inetpub\wwwroot\cgi-bin folder with the name hello.py.

    # hello.py
    print("Content-Type: text/html\n")  # The crucial header and a blank line
    print("<html>")
    print("<head>")
    print("<title>Hello from Python CGI!</title>")
    print("</head>")
    print("<body>")
    print("<h1>Hello, World!</h1>")
    print("<p>This page was generated by a Python CGI script.</p>")
    print("</body>")
    print("</html>")

Example 2: Handling Form Data

This script will display the data you send it from an HTML form.

  1. First, create an HTML form file. Save it in C:\inetpub\wwwroot (the main site root) as form.html.

    <!-- form.html -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>CGI Form</title>
    </head>
    <body>
        <h1>Enter Your Details</h1>
        <form action="/cgi-bin/process_form.py" method="post">
            Name: <input type="text" name="user_name">
            <br><br>
            Email: <input type="email" name="user_email">
            <br><br>
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
  2. Now, create the Python script to process this form. Save it in C:\inetpub\wwwroot\cgi-bin as process_form.py.

    # process_form.py
    import cgi
    import html
    # The crucial header and a blank line
    print("Content-Type: text/html\n")
    # Start of the HTML response
    print("<html>")
    print("<head><title>Form Results</title></head>")
    print("<body>")
    print("<h1>Form Submitted!</h1>")
    # Create an instance of FieldStorage to get form data
    form = cgi.FieldStorage()
    # Check if the form was submitted with data
    if "user_name" in form and "user_email" in form:
        # Use html.escape() to prevent Cross-Site Scripting (XSS) attacks
        name = html.escape(form.getvalue("user_name"))
        email = html.escape(form.getvalue("user_email"))
        print(f"<p>Hello, <strong>{name}</strong>!</p>")
        print(f"<p>The email address you provided is: {email}</p>")
    else:
        print("<p>Error: Form data was not received.</p>")
    print("</body>")
    print("</html>")

    Note: We use the cgi and html modules. cgi.FieldStorage() parses the form data, and html.escape() sanitizes the input to prevent malicious code injection.


Running and Testing

  1. Make sure the World Wide Web Publishing Service is running. You can find it in "Services" (services.msc).
  2. Open your web browser (Chrome, Firefox, Edge, etc.).
  3. Navigate to your form page:
    • http://localhost/form.html
    • You should see the input form. Fill it out and click "Submit".
  4. You will be redirected to the output from your process_form.py script, which should display the data you entered.
  5. You can also test the simple script directly:
    • http://localhost/cgi-bin/hello.py
    • You should see the "Hello, World!" page.

Troubleshooting Common Issues

Issue 1: 404.3 - Forbidden: MIME Type is not handled.

This is the most common error. It means IIS doesn't know how to handle .py files.

  • Solution: You likely missed Step 3.2 where you added the *.py handler mapping. Go back and add the Python.CgiHandler.

Issue 2: 500 - Internal Server Error

This means the script was executed, but it crashed or produced invalid output.

  • Check the Error Logs: This is your best friend. In IIS Manager, click on your server name -> Logging. The log file path is listed there. Open it in a text editor and look for recent errors.
  • Check for Syntax Errors: Did you forget a colon or a quote in your Python script?
  • Check the Blank Line: Did you remember to print Content-Type: text/html\n? The \n represents the blank line. This is the #1 cause of 500 errors for CGI.

Issue 3: The browser shows the raw Python code instead of executing it.

This means IIS is treating your script as a plain text file to download, not as an executable.

  • Solution: This is the same as the 404.3 error. You need to add the *.py handler mapping in Step 3.2.

Issue 4: python is not recognized as an internal or external command...

This error would appear in the IIS logs if it can't find the Python executable.

  • Solution: Make sure you checked "Add Python to PATH" during its installation. If you didn't, you can either reinstall Python or add the Python path (e.g., C:\Python39\) manually to your system's PATH environment variable.
分享:
扫描分享到社交APP
上一篇
下一篇