In this tutorial, we aim to guide you through setting up and activating a virtual environment for your Flask projects. You will learn how to create a virtual environment, install Flask into it, and how to activate and deactivate this environment. By the end of this tutorial, you will have a basic understanding of managing project-specific environments and dependencies.
Prerequisites:
- Basic knowledge of Python programming
- Flask installed on your system
- Access to a terminal/command line interface
A virtual environment is a tool that helps to keep dependencies required by different projects separate. It solves the “Project X depends on version 1.x, but Project Y needs 4.x” dilemma. It creates an environment that has its own installation directories and doesn’t share libraries with other virtual environments.
python3 -m venv env
(Replace "env" with your environment name)source env/bin/activate
.\\env\\Scripts\\activate
deactivate
in your shell.$ cd my_project_folder # navigate to project folder
$ python3 -m venv env # create virtual environment
On macOS and Linux:
$ source env/bin/activate
On Windows:
$ .\\env\\Scripts\\activate
$ deactivate
In this tutorial, we've learned the importance of virtual environments for managing separate dependencies across projects. We've also learned how to set up, activate, and deactivate these environments.
Next steps for learning could include exploring how to manage package dependencies within a virtual environment, and how to use Flask to create basic web applications.
For further reading, consult the official Python documentation on venv.
Solutions:
mkdir new_project && cd new_project
python3 -m venv new_env
source new_env/bin/activate
deactivate
Commands:
mkdir project_1 && cd project_1
python3 -m venv env1
source env1/bin/activate
pip install Flask==1.0.0
python -c "import flask; print(flask.__version__)"
(should output 1.0.0)deactivate
cd .. && mkdir project_2 && cd project_2
python3 -m venv env2
source env2/bin/activate
pip install Flask==1.1.0
python -c "import flask; print(flask.__version__)"
(should output 1.1.0)Remember to continue practicing with virtual environments to solidify your understanding!