Debian 上让 Apache 支持 Python 的主流做法有三种:使用 mod_wsgi 运行 WSGI 应用(推荐)、使用 CGI 方式运行脚本、以及使用已不推荐但仍有历史遗留的 mod_python。下面给出可直接落地的步骤与要点。
sudo apt update && sudo apt install apache2 python3 python3-pip libapache2-mod-wsgi-py3sudo a2enmod wsgifrom flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World from Flask via mod_wsgi"
if __name__ == "__main__":
app.run()
import sys
sys.path.insert(0, "/var/www/yourapp")
from app import app as application # 对象名必须为 application
<VirtualHost *:80>
ServerName yourdomain.com
WSGIDaemonProcess yourapp python-home=/var/www/yourapp/venv python-path=/var/www/yourapp
WSGIProcessGroup yourapp
WSGIScriptAlias / /var/www/yourapp/wsgi.py
<Directory /var/www/yourapp>
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
sudo a2ensite yourapp.conf && sudo systemctl restart apache2sudo a2enmod cgi#!/usr/bin/env python3
print("Content-Type: text/html")
print()
print("<html><body>Hello, World from CGI</body></html>")
sudo chmod +x /usr/lib/cgi-bin/hello.pyScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI
AddHandler cgi-script .py
Require all granted
</Directory>
sudo systemctl restart apache2curl http://localhost/cgi-bin/hello.pysudo apt-get install libapache2-mod-python libapache2-mod-python-docsudo a2enmod python<Location /mpinfo>
SetHandler mod_python
PythonHandler mod_python.testhandler
<IfModule mod_authz_core.c>
Require all granted
</IfModule>
</Location>
from mod_python import apache
def handler(req):
req.content_type = 'text/html'
req.send_http_header()
req.write('<html><body>Hello World from mod_python</body></html>')
return apache.OK
<Directory /var/www/py>
AddHandler mod_python .py
PythonHandler hello
PythonDebug On
</Directory>
sudo systemctl status apache2sudo apache2ctl configtesttail -f /var/log/apache2/error.logchmod +x;WSGI 目录需 Require all granted。pip install -r requirements.txt;如使用 .egg 包,设置可写的 PYTHON_EGG_CACHE。sudo ufw allow 'Apache Full'(或放行 80/443)。