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

配置Apache部署Flask应用报500错误:ImportError: No module named flask

Fixing "ImportError: No module named flask" When Deploying Flask on Apache

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:

  1. 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
  1. Navigate to your app directory and create a virtual environment:
cd /var/www/firstapp
# Python 2
virtualenv venv
# Python 3
python3 -m venv venv
  1. Activate the virtual environment and install Flask:
source venv/bin/activate
pip install Flask
deactivate
  1. Update your hello.wsgi to 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
  1. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:50:23