杰瑞科技汇

Xampp下Apache如何与Python协同工作?

Of course! This is a very common and useful setup. Integrating Python with XAMPP's Apache server allows you to run Python scripts as if they were web pages, enabling you to use powerful Python libraries (like for data analysis, machine learning, or web scraping) directly from your browser.

Xampp下Apache如何与Python协同工作?-图1
(图片来源网络,侵删)

Here’s a complete guide on how to set up and use Python with XAMPP's Apache server.

The Core Concept: The mod_wsgi Module

By default, Apache doesn't know how to execute Python code. To make it happen, we need to use a special module called mod_wsgi.

  • mod_wsgi is an Apache module that hosts Python applications, allowing Apache to serve dynamic content generated by Python scripts.
  • It acts as a bridge between your web server (Apache) and your Python interpreter.

There are two main ways to use mod_wsgi:

  1. Embedded Mode: mod_wsgi is compiled directly into the Apache process. This is simpler to set up but is less flexible and can be harder to debug.
  2. Daemon Mode (Recommended): mod_wsgi runs a separate, long-running Python process (a "daemon"). Apache communicates with this daemon to serve Python content. This is more efficient, more stable, and the industry standard.

We will focus on setting up the Embedded Mode first because it's the easiest way to get started and understand the concept.

Xampp下Apache如何与Python协同工作?-图2
(图片来源网络,侵删)

Method 1: Embedded Mode (Easiest for Beginners)

This method involves adding a few lines to your Apache configuration file to tell it how to handle .py files.

Step 1: Install mod_wsgi

First, you need to install the mod_wsgi module on your system. The version must match your Python and Apache versions.

  • On Windows:

    • Go to the official mod_wsgi download page: https://modwsgi.readthedocs.io/en/develop/installation.html
    • Scroll down to the "Binaries" section for Windows.
    • Download the .whl (Wheel) file that matches your system (32-bit or 64-bit) and Python version (e.g., cp311 for Python 3.11).
    • Open a Command Prompt as an Administrator.
    • Navigate to the directory where you downloaded the file.
    • Install it using pip. For example: pip install mod_wsgi‑4.9.72‑cp311‑cp311‑win_amd64.whl
  • On Linux (Debian/Ubuntu):

    Xampp下Apache如何与Python协同工作?-图3
    (图片来源网络,侵删)
    sudo apt update
    sudo apt install libapache2-mod-wsgi-py3

    This will automatically install the module and enable it for you.

  • On macOS (using Homebrew):

    brew install mod-wsgi

Step 2: Configure Apache

Now, we need to tell Apache to use this module.

  1. Find your Apache Configuration File:

    • In the XAMPP Control Panel, click the Config button next to Apache and select httpd.conf.
    • This will open the main Apache configuration file in a text editor (like Notepad++).
  2. Load the Module:

    • Press Ctrl+F and search for LoadModule. You will see a list of already loaded modules.
    • Add the following line at the end of the LoadModule section. The path might be slightly different on your system, so find the correct path by looking at where mod_wsgi.so was installed (e.g., in your Python Scripts folder or your Apache modules folder).
    # For Windows, the path will be something like this:
    LoadModule wsgi_module "C:/Python39/python.exe/mod_wsgi.py"
    # Or if it's in the Apache modules folder:
    # LoadModule wsgi_module modules/mod_wsgi-py39-win32.so
    # For Linux, it's usually:
    # LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
  3. Configure a Python Handler:

    • Add the following lines at the bottom of the httpd.conf file. This tells Apache that any file ending in .py should be executed as a WSGI script.
    # Add a handler for Python files
    <FilesMatch "\.py$">
        SetHandler wsgi-script
    </FilesMatch>
    # Optional: Set a timeout for your scripts (in seconds)
    WSGIScriptTimeout 30
  4. Save and Restart Apache:

    • Save the changes to httpd.conf.
    • In the XAMPP Control Panel, stop and then restart the Apache service.

Step 3: Create a Test Python Script

  1. Place a Python file in your XAMPP web root directory. This is usually C:/xampp/htdocs/.

  2. Create a file named hello.py and add the following code:

    def application(environ, start_response):
        status = '200 OK'
        output = b'Hello from Python! This is a dynamic web page.'
        response_headers = [('Content-type', 'text/plain'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]

    Note: The application function is the standard entry point for a WSGI application. It must be named application.

  3. Open your web browser and navigate to: http://localhost/hello.py

You should see the text: Hello from Python! This is a dynamic web page. If you see this, congratulations, it's working!


Method 2: Daemon Mode (Recommended for Production)

Daemon mode is more complex to set up but is much better for performance and reliability. It isolates your Python application from Apache.

Step 1: Install mod_wsgi (Same as before)

Make sure you have mod_wsgi installed as described in Method 1.

Step 2: Configure Apache for Daemon Mode

  1. Open your httpd.conf file (from XAMPP's Config menu).

  2. Add the following configuration at the bottom of the file. Read the comments carefully to understand what each part does.

    #---------------------------------------------------------------------
    # mod_wsgi Daemon Mode Configuration
    #---------------------------------------------------------------------
    # Define the path to your Python executable.
    # This is crucial for Windows.
    WSGIPythonHome "C:/Users/YourUser/AppData/Local/Programs/Python/Python311" # CHANGE THIS
    # On Linux, you might not need this line, or it could be:
    # WSGIPythonHome /usr/bin/python3
    # Define a daemon process. We'll call it 'my-python-app'.
    WSGIDaemonProcess my-python-app \
        python-home="C:/Users/YourUser/AppData/Local/Programs/Python/Python311" \ # CHANGE THIS
        processes=2 \
        threads=15 \
        display-name=%{GROUP}
    # Associate the 'my-python-app' daemon with a specific directory.
    # This tells Apache that any request for a file in 'C:/xampp/htdocs/myapp'
    # should be handled by our daemon.
    WSGIScriptAlias /myapp "C:/xampp/htdocs/myapp/app.wsgi" # CHANGE THIS PATH
    # Apply the daemon process to the directory.
    <Directory "C:/xampp/htdocs/myapp"> # CHANGE THIS PATH
        WSGIProcessGroup my-python-app
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
    </Directory>

    What you need to change:

    • WSGIPythonHome: Set this to the installation directory of your Python version.
    • WSGIDaemonProcess: Make sure the python-home matches your Python path.
    • WSGIScriptAlias: This is the URL path (/myapp) and the path to your WSGI entry point file (app.wsgi).
    • <Directory>: This must be the directory containing your application files.
  3. Save and Restart Apache.

Step 3: Create a Sample Project

Now, let's create the project structure that the configuration above expects.

  1. Inside C:/xampp/htdocs/, create a new folder named myapp.
  2. Inside myapp, create two files: app.wsgi and app.py.

File 1: C:/xampp/htdocs/myapp/app.py (Your main application logic)

# This is a simple Flask-like application, but we don't need Flask.
def simple_app(environ, start_response):
    """A simple WSGI application."""
    status = '200 OK'
    headers = [('Content-type', 'text/html; charset=utf-8')]
    start_response(status, headers)
    # You can access request data from environ
    html_content = f"""
    <html>
        <head><title>Python via Daemon Mode</title></head>
        <body>
            <h1>Hello from Python in Daemon Mode!</h1>
            <p>This page is served by a separate Python process, which is more efficient.</p>
            <p>Request Path: {environ['PATH_INFO']}</p>
        </body>
    </html>
    """
    return [html_content.encode('utf-8')]
# You can also have multiple functions and route them
def another_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return [b"This is another Python application.".encode('utf-8')]

File 2: C:/xampp/htdocs/myapp/app.wsgi (The WSGI entry point)

This file tells mod_wsgi which function from your Python code to run.

import sys
# Add the directory containing your app.py to the Python path
sys.path.insert(0, 'C:/xampp/htdocs/myapp') # CHANGE THIS IF NEEDED
# Import your application function from app.py
from app import simple_app
# This is the variable mod_wsgi will look for.
# Assign your application function to it.
application = simple_app
# If you wanted to use 'another_app', you would do:
# application = another_app
  1. Open your browser and navigate to: http://localhost/myapp

You should see the HTML page generated by your Python script running in a dedicated daemon process.

Troubleshooting Common Issues

  • Internal Server Error (500):

    • Check your Apache error.log file (in C:/xampp/apache/logs/). It will contain the exact Python error traceback, which is the key to fixing the problem.
    • Make sure your Python syntax is correct.
    • Ensure all file paths in httpd.conf are correct.
    • On Windows, make sure WSGIPythonHome points to the correct Python directory.
  • Forbidden Error (403):

    • This is usually a permissions issue. Make sure the user that Apache is running as (e.g., SYSTEM on Windows) has read/execute permissions for your Python files and their directories.
    • Check the Require all granted directive in your <Directory> block.
  • The requested URL was not found on this server (404):

    • Double-check the URL you are typing in the browser.
    • Ensure that WSGIScriptAlias and the <Directory> block in httpd.conf point to the correct paths.
分享:
扫描分享到社交APP
上一篇
下一篇