You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Apache+mod_wsgi部署Flask应用遇模块导入错误,求排查方案

Fixing "ImportError: No module named project" in Flask + Apache + mod_wsgi Deployment

Let's break down the issues you're facing and walk through step-by-step fixes. That ImportError usually boils down to path problems, virtual environment misconfiguration, or mod_wsgi/Python version mismatches. Here's how to tackle each:

1. First: Confirm Your Project Directory Structure

First, double-check that your files are organized correctly—this is critical for imports to work. Your setup should look something like this:

/var/www/myapp/
├── env/                  # Your virtual environment
├── project/              # Your Flask app root folder (must have __init__.py!)
│   ├── __init__.py       # Where you define `app = Flask(__name__)`
│   └── (other app files)
└── myapp.wsgi            # Your WSGI script

If your project is a single file (project.py) instead of a folder, that's okay—but the folder structure is more standard for Flask apps.

2. Fix the WSGI Script: Add Your Project Path to Python's sys.path

The most common culprit here is that your project directory isn't in Python's module search path. Even if you activate the virtual environment, Python can't find project unless you explicitly tell it where to look. Update your myapp.wsgi to this:

import sys
import os

# Add the root of your app to Python's path
sys.path.insert(0, '/var/www/myapp')

# Activate the virtual environment (more reliable approach)
virtual_env_path = os.path.join('/var/www/myapp', 'env')
activate_this = os.path.join(virtual_env_path, 'bin', 'activate_this.py')

try:
    with open(activate_this) as file_:
        exec(file_.read(), dict(__file__=activate_this))
except Exception as e:
    # Log activation errors to Apache's error log for debugging
    import logging
    logger = logging.getLogger(__name__)
    logger.error(f"Failed to activate virtual environment: {str(e)}")

# Import your Flask app
from project import app as application

3. Alternative: Configure Virtual Environment Directly in Apache

Instead of relying on activate_this.py, you can tell Apache/mod_wsgi exactly where your virtual environment lives. This avoids potential issues with the activation script. Update your virtual host config:

<VirtualHost *:80>
    ServerName myapp.com

    # Point mod_wsgi to your virtual environment's Python
    WSGIPythonHome /var/www/myapp/env
    # Add your app's root directory to the module path
    WSGIPythonPath /var/www/myapp

    WSGIScriptAlias / /var/www/myapp/myapp.wsgi

    # Restrict directory access to your app's folder (not the root myapp folder)
    <Directory /var/www/myapp/project>
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

If you use this approach, you can simplify your myapp.wsgi to just:

import sys
sys.path.insert(0, '/var/www/myapp')
from project import app as application

4. Verify mod_wsgi is Compatible with Python 3.5

You mentioned uncertainty about mod_wsgi matching Python 3.5—let's confirm that:

Method 1: Check the mod_wsgi module file

Run this command to see which Python version your mod_wsgi is built for:

ls /usr/lib/apache2/modules/ | grep mod_wsgi

Look for a file like mod_wsgi-py35.so—the py35 part confirms it's built for Python 3.5.

Method 2: Create a test WSGI script to check Python version

Make a test.wsgi file in /var/www/myapp/:

import sys

def application(environ, start_response):
    status = '200 OK'
    output = f"Python Version: {sys.version}".encode('utf-8')
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]

Temporarily update your virtual host's WSGIScriptAlias to point to /var/www/myapp/test.wsgi, restart Apache, and visit your site. You'll see the Python version mod_wsgi is using—make sure it's 3.5.

If it's not the right version, you'll need to reinstall mod_wsgi specifically for Python 3.5 (on Debian/Ubuntu, that's sudo apt-get install libapache2-mod-wsgi-py3—but double-check it targets 3.5 for your distro).

5. Fix File Permissions

Apache runs as the www-data user (usually), so it needs read access to your app files and virtual environment. Run these commands to set correct permissions:

# Give Apache ownership of your app directory
sudo chown -R www-data:www-data /var/www/myapp
# Set read/execute permissions for Apache
sudo chmod -R 755 /var/www/myapp

6. Final Step: Restart Apache

After making any changes, restart Apache to apply them:

sudo systemctl restart apache2

Check your Apache error log again (tail -f /var/log/apache2/error.log) while accessing the site—if the import error is gone, you're good to go! If not, the log should give more specific clues about what's missing.

内容的提问来源于stack exchange,提问作者heapOverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:12:36