How to Install Flask: A Beginner’s Guide
Flask is a popular lightweight web framework written in Python. It is known for its simplicity and flexibility, making it a favorite among developers who want to quickly build web applications.
Prerequisites
- Python installed on your system (version 3.6 or higher recommended). You can download it from the official Python website.
- Basic knowledge of the command line (Terminal on Mac/Linux, Command Prompt or PowerShell on Windows).
- Optional but recommended: a virtual environment tool to keep your project dependencies isolated.
Step 1: Verify Python Installation
First, check if Python is installed and accessible from your command line.
python --version
Or on some systems:
python3 --version
If you see a Python version 3.x.x, you’re good to go. Otherwise, install Python as noted above.
Step 2: Create a Virtual Environment (Recommended)
Using a virtual environment helps manage packages for each project independently. Here’s how you can create one:
- Navigate to your project folder or create one:
mkdir myflaskapp
cd myflaskapp
python -m venv venv
- On Windows:
venv\Scripts\activate
source venv/bin/activate
Step 3: Install Flask Using pip
With your virtual environment activated (or not if you skipped step 2), install Flask using pip:
pip install Flask
This command downloads and installs the latest Flask version from the Python Package Index.
Step 4: Verify Flask Installation
To confirm Flask installed correctly, run Python and try importing Flask:
python
>>> import flask
>>> print(flask.__version__)
If this prints the Flask version without errors, the installation was successful.
Step 5: Create a Simple Flask App
Let’s create a basic Flask application to test everything works:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Save this as app.py in your project directory.
Step 6: Run Your Flask Application
Run your app with this command:
python app.py
Visit http://127.0.0.1:5000/ in your web browser. You should see “Hello, Flask!” displayed.
Troubleshooting
- pip not found: Ensure Python’s Scripts directory is in your system PATH or use
python -m pip install Flask. - Virtual environment activation fails: Check your shell and OS-specific activation commands.
- Permission errors: Avoid installing packages globally with sudo; use virtual environments.
Summary Checklist
- Python 3 installed and accessible
- Virtual environment created and activated (recommended)
- Flask installed via pip
- Flask import verified
- Simple Flask app created and run locally
For more Python web development tutorials, check out our article on how to install Django Rest Framework.
By following these steps, you set up Flask quickly and can start building your web applications confidently. Happy coding!
