Relocating virtual environment project from local to server (flask project), have to install dependencies again?

0

Issue

I have created a flask application in a virtual environment on my local machine and I could run it locally (at http://localhost:5000).

I then put this project in a repo and I then went to my server and git clone this project.

All files are identical on my local machine and in my server.

I then wanted to test this virtual environment on the server by trying .venv/bin/activate

However I ran into an error. It says I do not have flask!:

Traceback (most recent call last):
  File "__init__.py", line 1, in <module>
    from flask import Flask
ImportError: No module named flask

I am assuming that I have to initialize something in the virtual environment first, like installing all of the dependencies. Or do I have to pip install flask again? (It would be kind of funny to do that…)

Solution

As a general rule python environments are not portable across machines.

This means that you cannot reliably expect to port the virtual environment across machines. This is especially true if you are moving stuff between different operating systems. For example, a virtual environment created in Windows will not work in Linux.

Similarly, a virtual environment created in OSX will not work in Linux. Sometimes, you can get Linux > Linux compatibility, but this is by chance and not to be relied upon.

The reasons are numerous – some libraries need to be built against native extensions, others require compatible system libraries in place to work, etc.

So, the most reliable workflow is the following:

  1. You can (but I would recommend against this) put your virtual environment in the same directory as your project. If you do so, make sure you don’t add the virtual environment root directory to your source control system. It is best to separate your virtual environments from your source code (see the virtualenvwrapper project project for a great way to manage your virtual environments separately).

  2. You should create a requirements file, by running pip freeze > requirements.txt. Keep this file updated and add it to your source control system. In your target system, simply create an empty virtual environment and then pip install -r requirements.txt to make sure all requirements are installed correctly. Doing so will make sure that any native extensions are also built and installed.

Answered By – Burhan Khalid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More