杰瑞科技汇

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

Of course. The combination of Python, Apache, and Windows is a very common and powerful setup for web development and hosting. This guide will walk you through what each component does, why you'd use them together, and the most common ways to set them up.

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

Understanding the Three Components

Think of this as a restaurant:

  • Python: The Chef. It's the master of logic and flavor. It takes raw ingredients (user requests, data) and follows recipes (your code) to create delicious dishes (web pages, API responses).
  • Apache: The Maître d' / Host. It's the first person to greet customers (web browsers). It doesn't cook, but it takes their orders, manages the dining room (ports, security), and delivers the orders to the right kitchen (Python). It's responsible for serving static files (like images, CSS) and forwarding dynamic requests to the chef.
  • Windows: The Restaurant Building / Operating System. It's the physical location and the underlying infrastructure that allows the Maître d' and the Chef to operate.

Why use this combination?

  • Stability & Maturity: Apache is a battle-tested, reliable web server.
  • Power of Python: You can use Python's vast ecosystem (Django, Flask, Pandas, NumPy, etc.) to build complex, data-driven applications.
  • Enterprise Environment: Many companies use Windows Server as their standard OS for hosting internal and public applications.

The Core Challenge: How Apache and Python Talk

Apache is written in C and doesn't understand Python natively. To make them work together, you need a "bridge" or "interpreter" that can translate Apache's requests into a language Python understands. This bridge is called a Gateway Interface.

The two most common interfaces for this are:

Windows下Python与Apache如何协同工作?-图2
(图片来源网络,侵删)
  1. mod_wsgi (Recommended): This is an Apache module that embeds Python directly into the Apache process. It's highly efficient, secure, and the standard for production environments. It's like having a chef who works right in the restaurant's kitchen.
  2. CGI (Common Gateway Interface): This is an older, simpler method. For each request, Apache starts a completely separate Python process, runs your script, and then kills the process. It's very inefficient and not recommended for anything but the simplest scripts. It's like hiring a new chef for every single order.

For any serious project, you should use mod_wsgi.


Setup Guide (Using mod_wsgi)

This is the most robust and recommended method for Windows.

Step 1: Install Prerequisites

  1. Install Python: If you haven't already, download and install Python from the official website. During installation, check the box that says "Add Python to PATH". This is crucial.
  2. Install Apache: Download the latest version of Apache for Windows from the Apache Lounge (they provide pre-compiled binaries that are easier to use on Windows).
    • Extract the downloaded zip file to a simple location, like C:\Apache24.
    • Open a Command Prompt as an Administrator and navigate to the bin directory: cd C:\Apache24\bin.
    • To install Apache as a Windows service, run: httpd -k install
    • You can start the service with: httpd -k start
    • You can test if it's working by opening your browser and going to http://localhost. You should see the "It works!" page.

Step 2: Install mod_wsgi

This is the trickiest part on Windows because you need a version of mod_wsgi that matches your Python version and architecture (32-bit or 64-bit).

  1. Find your Python info:

    Windows下Python与Apache如何协同工作?-图3
    (图片来源网络,侵删)
    • Open a Command Prompt and run python --version. Note the version (e.g., 3.10).
    • Run python -c "import struct; print(struct.calcsize('P') * 8)". This will tell you if it's 32-bit (it prints 32) or 64-bit (it prints 64).
  2. Download the correct mod_wsgi:

    • Go to the mod_wsgi Windows binaries page: https://www.modwsgi.org/downloads/
    • Download the .whl (Wheel) file that matches your Python version and architecture. For example, if you have Python 3.10 64-bit, you'd download mod_wsgi‑4.9.1‑cp310‑cp310‑win_amd64.whl.
  3. Install mod_wsgi:

    • Open a Command Prompt as an Administrator.
    • Navigate to the directory where you downloaded the .whl file.
    • Install it using pip: pip install mod_wsgi‑4.9.1‑cp310‑cp310‑win_amd64.whl (use the actual filename you downloaded).

Step 3: Configure Apache to Use mod_wsgi

  1. Copy the mod_wsgi file:

    • Find where pip installed mod_wsgi. It's usually in your Python's Scripts folder or site-packages folder. Look for a file named mod_wsgi.cp310-win_amd64.pyd (the name will vary).
    • Copy this .pyd file into your Apache modules directory: C:\Apache24\modules\.
  2. Edit httpd.conf:

    • Open the Apache configuration file: C:\Apache24\conf\httpd.conf.

    • Load the module: Add the following line near the other LoadModule statements (usually at the top of the file). Make sure the path to the .pyd file is correct.

      LoadModule wsgi_module modules/mod_wsgi.cp310-win_amd64.pyd
    • Add a WSGI configuration section: At the end of the httpd.conf file, add a section to define your application. Let's say you have a Flask app in C:\my_project\app.py.

      <VirtualHost *:80>
          ServerName localhost
          DocumentRoot "C:/my_project"
          # WSGI configuration for a Flask application
          WSGIDaemonProcess my_app python-home="C:/Python310" python-path="C:/my_project"
          WSGIScriptAlias / "C:/my_project/app.wsgi"
          <Directory "C:/my_project">
              Require all granted
          </Directory>
      </VirtualHost>
      • WSGIDaemonProcess: This tells Apache to create a separate process for your app.
        • my_app: A name for your process.
        • python-home: The path to your Python installation.
        • python-path: The path to your project's root directory (where your app.py is).
      • WSGIScriptAlias: This maps a URL path to your WSGI script file.
        • The root URL.
        • "C:/my_project/app.wsgi": The path to the WSGI entry point file you'll create next.

Step 4: Create the WSGI Entry Point File

Create a new file named app.wsgi in your project directory (C:\my_project\).

For a Flask app, it would look like this:

# C:\my_project\app.wsgi
# Add your project directory to the Python path
import sys
sys.path.insert(0, 'C:/my_project')
# Import your Flask application instance
from app import app as application
# The 'application' variable must point to your WSGI app
# This is what mod_wsgi will look for.

For a Django app, it would be:

# C:\my_project\myproject\wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()

Step 5: Restart Apache and Test

  1. Open Command Prompt as an Administrator.
  2. Navigate to C:\Apache24\bin.
  3. Restart Apache: httpd -k restart
  4. Open your browser and go to http://localhost. Your Python web application should now be running, served by Apache!

Alternative: Easier Development Setup (Not for Production)

Setting up mod_wsgi can be complex. For local development only, you can use a simpler approach with Python's built-in server.

  1. Install Python: Make sure Python is installed and in your PATH.

  2. Create a simple Python app: Save this as app.py.

    from http.server import HTTPServer, SimpleHTTPRequestHandler
    class MyHTTPRequestHandler(SimpleHTTPRequestHandler):
        def end_headers(self):
            self.send_header('Access-Control-Allow-Origin', '*')
            super().end_headers()
    if __name
分享:
扫描分享到社交APP
上一篇
下一篇