配置Apache部署Flask应用报500错误:ImportError: No module named flask
Ah, this is a super common gotcha when getting Flask up and running with Apache! The root of the problem is that you installed Flask using pip install --user Flask—this puts the Flask package in your personal user's private Python directory. But Apache runs under the www-data system user, which doesn't have access to that folder. Let's fix this with one of these straightforward solutions:
Option 1: Install Flask Globally (Quickest Fix)
The simplest way is to install Flask system-wide so all users (including www-data) can access it. Run this command:
sudo pip install Flask
Note: If your system defaults to Python 3, you might need to use pip3 instead of pip—check with which python to confirm your active version.
Option 2: Point Apache to Your User's Package Directory
If you prefer not to install packages globally, you can tell Apache where to find your user-installed Flask. First, find the path to your user's Python site-packages:
python -m site --user-site
This will output something like /home/your_username/.local/lib/python2.7/site-packages.
Next, edit your hello.wsgi file to add this path to Python's system path:
import sys sys.path.insert(0, "/var/www/firstapp") # Add the path you just copied here sys.path.insert(0, "/home/your_username/.local/lib/python2.7/site-packages") from hello import app as application
Then restart Apache to apply the changes:
sudo service apache2 restart
Option 3: Use a Virtual Environment (Best Practice)
For cleaner dependency management (and to avoid messing with system packages), using a virtual environment is the way to go:
- First, install the virtual environment tool for your Python version:
# For Python 2 sudo apt-get install python-virtualenv # For Python 3 sudo apt-get install python3-venv
- Navigate to your app directory and create a virtual environment:
cd /var/www/firstapp # Python 2 virtualenv venv # Python 3 python3 -m venv venv
- Activate the virtual environment and install Flask:
source venv/bin/activate pip install Flask deactivate
- Update your
hello.wsgito use the virtual environment's packages:
import sys sys.path.insert(0, "/var/www/firstapp") # Add the virtual environment's site-packages path sys.path.insert(0, "/var/www/firstapp/venv/lib/python2.7/site-packages") from hello import app as application
- Restart Apache to load the new configuration:
sudo service apache2 restart
Quick Permission Check
While you're at it, make sure the www-data user has access to your app directory:
sudo chown -R www-data:www-data /var/www/firstapp sudo chmod -R 755 /var/www/firstapp
内容的提问来源于stack exchange,提问作者pinkraindancer

