Skip to main content

Getting started with Flask: building your first web application

Learn how to create your first web application using Flask, Python's lightweight web framework

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

This tutorial assumes you have Python 3.8 or later installed on your system. If you haven't installed Python yet, visit [python.org](https://python.org) to download and install the latest version.

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

Always use virtual environments for Python projects to keep dependencies isolated and maintain a clean development environment.

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:

  1. We import the Flask class from the flask package
  2. We create a new Flask application instance
  3. We define a route using the @app.route() decorator
  4. We create a function that returns our content
  5. 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

Flask uses the Jinja2 templating engine by default. The `{% %}` syntax you see in the HTML files is Jinja2 template syntax, which allows you to create dynamic HTML pages.

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

The double curly braces `{{ }}` in templates are used to output variable values. You can pass any Python object from your route to the template using the `render_template()` function.

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

Remember that while debug mode is helpful during development, it should never be enabled in a production environment as it can expose sensitive information about your application.

Common issues and solutions

Here are some common issues you might encounter:

  1. Application not reloading: If your application isn't automatically reloading when you make changes, ensure debug=True is set in app.run().
  2. Template not found: Make sure your templates are in the templates directory and the filenames match exactly.
  3. 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.