Flask Development Environment: Virtual Environment Setup and Dependency Management

This article introduces the necessity of Python virtual environments and the usage of the `venv` tool. Different projects may have conflicting dependency versions (e.g., Project A requires Flask 2.0 while Project B requires 1.0). Virtual environments can isolate the operating environments of different projects, preventing global dependency conflicts and allowing each project to have its own independent "small repository." `venv` is a built-in tool for Python 3.3+ and does not require additional installation, making it suitable for beginners. Usage steps: After creating a project directory, execute `python -m venv venv` to generate the virtual environment. Activation commands vary by system (Windows CMD/PowerShell, Mac/Linux), and the command line will display `(venv)` after activation. When activated, use `pip install flask` to install dependencies and verify with `flask --version`. After development, export dependencies using `pip freeze > requirements.txt`, and restore them with `pip install -r requirements.txt`. To exit the environment, run `deactivate`. Common issues: Activation commands differ by system; if the environment is corrupted, delete the `venv` folder and recreate it. `venv` effectively avoids dependency conflicts and ensures project stability and reproducibility.

Read More