Search code examples
pythonflaskmod-wsgiwsgipython-venv

Python Flask using mod_wsgi in Apache; how to get venv to work?


I've been trying to get this to work, and have searched everywhere and read page up and page down, but doesn't seem to find an answer.

I have Apache with mod_wsgi and a simple test Flask application.

I got it working using this: https://www.jakowicz.com/flask-apache-wsgi/

Then I somehow found that Apache mod_wsgi used the system python and I want to use venv (https://docs.python.org/3/library/venv.html).

My application is in a directory with the normal directory structure of the venv, but how do I get my application to use that?

I found this: http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html

But if I put in python-home my application fails.

A couple of questions: How do I find the Python version that my app is using? How do I find my mod_wsgi version? How do I get my app to use my venv?

I'm new to Python and WSGI, I have mostly worked with PHP.

Hope someone can explain to me what to do...

-- Ronni


Solution

  • Continuing the discussion in the comment section of your question:

    Assume the following directory with a virtual environment created in the folder /venv:

    - main.py
    - /static
      - /js
      - /html
      - /css
    - /venv
      - /bin
        - activate
    

    To activate the virtual environment, thus using the local copy of Python (as opposed to your global copy), the following command must be used:

    . /venv/bin/activate

    the . essentially tells the terminal window that the activate file, located at /venv/bin (assuming we're in the top level of the above directory), must be executed. You'll know that the command is successful when you see the string (venv) at the start of a new line in your terminal window.

    Now, the which command will confirm that you're now using the local copy of Python:

    which python

    Now your virtual environment is activated, you can use pip to install any module you wish locally to this virtual environment. You can specify to install a certain version of a module if you wish, or just grab the latest. The version of Flask or Apache that you install depends on what you specify when installing.

    Lastly, the command python --version will tell you the version of this copy of Python 2. python3 --version will do the same for Python 3. Whenever you execute a script using this local copy of Python, it will be using this Python version.

    To get Python version from within a script:

    from sys import version_info   
    print version_info
    

    Output (will depend on your version, but will look something like this):

    sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)