Flask is a lightweight and flexible web framework for Python that allows you to build web applications quickly and efficiently. In this tutorial, we'll create a simple web application that will introduce you to Flask's core concepts and get you started with web development in Python.
Note
Prerequisites
Before we begin, you should have:
- Basic Python programming knowledge
- Familiarity with HTML
- A text editor or IDE of your choice
- Command line/terminal basics
Setting up your development environment
First, let's create a new project directory and set up a virtual environment to manage our dependencies.
# Create a new project directory
mkdir flask-hello-world
cd flask-hello-world
# Create and activate a virtual environment
python -m venv venv
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate
Tip
Now, let's install Flask:
pip install flask
Creating your first Flask application
Let's create a simple application that displays a welcome message. Create a new file called app.py:
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define our first route
@app.route('/')
def hello_world():
return '<h1>Hello, Flask!</h1>'
# Add this if block to run the application
if __name__ == '__main__':
app.run(debug=True)
Let's break down what's happening in this code:
- We import the Flask class from the flask package
- We create a new Flask application instance
- We define a route using the
@app.route()decorator - We create a function that returns our content
- We add a conditional to run the application in debug mode
Running your application
To run your application, use the following command in your terminal:
python app.py
You should see output similar to this:
* Serving Flask app 'app'
* Debug mode: on
* Running on http://127.0.0.1:5000
Visit http://127.0.0.1:5000 in your web browser, and you'll see your "Hello, Flask!" message.
Adding more routes and templates
Let's make our application more interesting by adding multiple pages and HTML templates.
First, create a templates directory in your project folder:
mkdir templates
Create a new file templates/base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %} - Flask Tutorial</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
nav {
margin-bottom: 20px;
}
</style>
</head>
<body>
<nav>
<a href="/">Home</a> |
<a href="/about">About</a>
</nav>
{% block content %}{% endblock %}
</body>
</html>
Now create templates/home.html:
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to Flask</h1>
<p>This is your first Flask application!</p>
{% endblock %}
And templates/about.html:
{% extends 'base.html' %}
{% block title %}About{% endblock %}
{% block content %}
<h1>About</h1>
<p>This page was created as part of the Flask tutorial.</p>
{% endblock %}
Update your app.py to use these templates:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
Important
Adding dynamic content
Let's modify our home page to display dynamic content. Update your app.py:
from flask import Flask, render_template
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html', current_time=datetime.now())
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
And update templates/home.html:
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to Flask</h1>
<p>This is your first Flask application!</p>
<p>The current time is: {{ current_time.strftime('%Y-%m-%d %H:%M:%S') }}</p>
{% endblock %}
Tip
Next steps
Congratulations! You've created your first Flask web application. Here's what you've learned:
- Setting up a Flask development environment
- Creating routes and views
- Using templates for HTML pages
- Passing dynamic content to templates
To continue learning Flask, you might want to explore:
- Handling form submissions
- Working with databases
- User authentication
- RESTful API development
- Deploying Flask applications
Warning
Common issues and solutions
Here are some common issues you might encounter:
- Application not reloading: If your application isn't automatically reloading when you make changes, ensure
debug=Trueis set inapp.run(). - Template not found: Make sure your templates are in the
templatesdirectory and the filenames match exactly. - Import errors: Verify that Flask is installed in your virtual environment by running
pip freeze | grep Flask.
Resources for further learning
Remember to keep practising and gradually build more complex applications as you become comfortable with the basics. Flask's simplicity makes it an excellent framework for learning web development, while its flexibility allows it to scale for larger applications.