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\\activatedeactivate 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_projectpython3 -m venv new_envsource new_env/bin/activatedeactivate
Commands:
mkdir project_1 && cd project_1python3 -m venv env1source env1/bin/activatepip install Flask==1.0.0python -c "import flask; print(flask.__version__)" (should output 1.0.0)deactivatecd .. && mkdir project_2 && cd project_2python3 -m venv env2source env2/bin/activatepip install Flask==1.1.0python -c "import flask; print(flask.__version__)" (should output 1.1.0)Remember to continue practicing with virtual environments to solidify your understanding!