Virtual Environment for Python Django
Without virtual environments, all your projects will use the same installed packages.
When you want to move a project to a server when it's done, you don't know which packages are needed for this project, so your only option is to also install all of those packages there. It will quickly become a long list and many of the packages won't be necessary for that particular project.
When using a virtual environment, you have a set of installed packages for each project, and they don't mix. Much nicer.
You can start using virtual env now. In your project directory, do:
pip install virtualenv
Now you have the virtualenv command (for all projects).
virtualenv env
Now you have a directory "env" in your project directory that will contain this project's virtualenv.
env\Scripts\activate
Now you are using this virtualenv (your prompt changed to reflect that).
pip install django
Installs Django only for this project.
pip freeze
Shows you which packages are installed, now only for this project.
pip freeze > requirements.txt
Creates a requirements.txt that you can use to remember which packages need installing, and as input for
pip install -r requirements.txt
That installs them. And that's more or less all you need.
Well, this is one of the most common questions among beginners. I, myself have faced the question and did build multiple projects without worrying about the virtual environment.
But, of late, I have realized the importance of using virtual environments. Some of the benefits of using virtual environments are:
- Dependency Management: Prevent conflicts between dependencies of multiple projects.
- Ease of installation and setting up new project on different machines: Store your dependencies in requirements.txt file and run
pip install -r requirements.txt
to install the dependencies wherever you want.
In java all libs used can be packed into a war or jar file. The advantage is that you don't need to worry about the environments of the OS.
Python is a pure dynamic language. Without virtual environment, all the python libs need to be installed into system path and shared among all python project.
Imagine that you are developing a django 1.10 project. You find a demo project. You want to run it on your machine. But it is compatible only with django 1.8. You can not install two version of the same lib in the same machine, so you get stuck.
Virtual environment solves problem like this.
But of course virtual environment is not perfect. There are python libs like mysql-python which depends on libmysqld. If those libs are used in your project, it cannot be totally independent with the settings in OS. The best practice I think is to use virtual machine combined with docker. IDE like pycharm supports running remotely via docker