Table of Contents
Flask is a lightweight and flexible web framework for Python that allows developers to create web applications quickly and efficiently. This tutorial guides you through setting up a Flask project from scratch, suitable for beginners and experienced programmers alike.
Prerequisites
- Python installed on your system (version 3.6+)
- Basic knowledge of Python programming
- Text editor or IDE (such as VS Code, PyCharm, or Sublime Text)
- Command line or terminal access
Step 1: Create a Project Directory
Start by creating a new directory for your Flask project. Open your terminal and run:
mkdir flask_project
Navigate into the directory:
cd flask_project
Step 2: Set Up a Virtual Environment
Creating a virtual environment helps manage dependencies. Run:
python -m venv venv
Activate the virtual environment:
On Windows:
venv\Scripts\activate
On macOS/Linux:
source venv/bin/activate
Step 3: Install Flask
With the virtual environment activated, install Flask using pip:
pip install Flask
Step 4: Create the Application File
Create a new file named app.py in your project directory. This file will contain your Flask application code.
Open app.py and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run(debug=True)
Step 5: Run the Flask Application
In your terminal, ensure your virtual environment is active, then run:
python app.py
You should see output indicating the server is running, typically at http://127.0.0.1:5000/.
Step 6: View Your Application
Open your web browser and navigate to http://127.0.0.1:5000/. You should see the message Hello, Flask! displayed on the page.
Next Steps
From here, you can expand your Flask application by adding templates, static files, and more routes to build a complete web app.