flaskpackagedebianvirtualenvmod-wsgi

Apache mod_wsgi flask application using global jinja2 package instead of the one installed in the virtual environment


I am configuring a Flask Application on a Debian 12 server, which is supposed to run with python 3.6.9 and Jinja2 Version 3.0.3 in a local venv. But instead of using it, it seems to access the global one installed in /usr/lib/python3/dist-packages/jinja2

(venv) root@xxxxx:/var/www# pip show 
Jinja2Name: Jinja2Version: 3.0.3
Location: /var/www/xxx.xxxx.de/venv/lib/python3.6/site-packages
Requires: MarkupSafeRequired-by: Flask, Flask-Babel, mkdocs

while all other packages seems to be used correctly crom the venv, only for Jinja2, the global package (version 3.1.2) is used, and I don't know why.

Error log of the flask application:

[Tue Jan 28 12:35:18.427107 2025] [wsgi:error] [pid 1938480:tid 1938487] [client xx.xx.xx.xx:52226]   File "/var/www/xxx.xxxx.de/venv/lib/python3.6/site-packages/flask_moment.py", line 3, in <module>, referer: https://xxx.xxxx.de/
[Tue Jan 28 12:35:18.427124 2025] [wsgi:error] [pid 1938480:tid 1938487] [client xx.xx.xx.xx:52226]     from jinja2 import Markup, referer: https://xxx.xxxx.de/
[Tue Jan 28 12:35:18.427149 2025] [wsgi:error] [pid 1938480:tid 1938487] [client xx.xx.xx.xx:52226] ImportError: cannot import name 'Markup' from 'jinja2' (/usr/lib/python3/dist-packages/jinja2/__init__.py), referer: https://xxx.xxxx.de/

As one can see from the logs, the virtual environment correctly uses its local flask_moment, but for the Jinja2 package it accesses the global dist-packages. What could be the reason?

The wsgi:

#! /var/www/xxx.xxxx.de/venv/bin/python
# -*- coding: utf-8 -*-
 
import sys

sys.path.append('/var/www/xxx.xxxx.de/app')
sys.path.append('/var/www/xxx.xxxx.de/venv/lib/python3.6/site-packages')

from bedarfsrechner import app as application

The apache configuration related to WSGI is

  ServerName  xxx.xxxx.de

  # directory where usually all the static html files go
  DocumentRoot /var/www/xxx.xxxx.de/htdocs
   
  # configure WSGI adapter
  WSGIScriptAlias / /var/www/xxx.xxxx.de/app/thewsginame.wsgi


<Directory /home/www/xxx.xxxx.de/app/>
    WSGIProcessGroup testbedarfsrechner 
    WSGIApplicationGroup %{GLOBAL}
    WSGIScriptReloading On
    Order deny,allow
    Allow from all
  </Directory>

Solution

  • (Based on the comment). You need you venv first in sys.path, before Python standard directories:

    sys.path.insert(0, '/var/www/xxx.xxxx.de/venv/lib/python3.6/site-packages')
    

    instead of sys.path.append.