Flask is a popular micro web framework for Python. To manage dependencies and avoid conflicts, it is a good practice to set up a virtual environment for your Flask projects. This article explains the steps to create and use a virtual environment with a real example.
Ensure you have Python installed on your system. You can download it from the official Python website (https://www.python.org/). For this example, we'll assume Python 3.x is installed.
Virtualenv is a tool to create isolated Python environments. To install it, open your terminal and run:
pip install virtualenv
To verify the installation, you can run:
virtualenv --version
Create a folder for your Flask project. For example:
mkdir flask_project cd flask_project
Inside your project directory, create a virtual environment by running:
virtualenv venv
This will create a folder named venv
containing the isolated environment.
Activate the virtual environment using the following command:
On Windows:
venv\Scripts\activate
On macOS/Linux:
source venv/bin/activate
After activation, your terminal prompt should show the name of the virtual environment, like (venv)
.
With the virtual environment activated, install Flask using pip:
pip install flask
You can verify the installation by checking the Flask version:
flask --version
Create a file named app.py
in your project directory with the following content:
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, Flask!" if __name__ == "__main__": app.run(debug=True)
With the virtual environment still activated, run the application:
python app.py
Your Flask application should start, and you can access it in your browser at http://127.0.0.1:5000/.
When you are done working, deactivate the virtual environment by running:
deactivate
By following these steps, you have successfully set up a virtual environment for a Flask project. This approach ensures that your project's dependencies are isolated and do not interfere with other projects.