Flask

Displaying Data from a Database in Flask


Introduction

Flask makes it easy to retrieve data from a database and display it in your web applications. In this guide, we'll explore how to fetch data from a database using SQLAlchemy in Flask and display it in your templates. You'll learn how to create routes, query the database, and render data in your HTML templates.

Step 1: Setting Up Your Flask Application

Before displaying data from a database, make sure you have a Flask application with SQLAlchemy configured. If not, you can create a basic Flask app like this:

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
db = SQLAlchemy(app)
        

Ensure you have Flask-SQLAlchemy installed and specify the database URI for your SQLite database.

Step 2: Creating a Model

To represent the data in your database, create a Python class as a model. Here's an example of a simple model for a `Task` with a title and description:

class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text, nullable=True)
        

In this example, we define a `Task` model with fields for `id,` `title,` and `description.` The model class inherits from db.Model, and the fields are defined as class attributes.

Step 3: Querying the Database

Create a route in your Flask application to query the database and fetch data. For example:

@app.route('/tasks')
def display_tasks():
    tasks = Task.query.all()
    return render_template('tasks.html', tasks=tasks)
        

In this route, we query all the tasks from the database using Task.query.all() and pass the results to an HTML template for rendering.

Step 4: Creating an HTML Template

Create an HTML template to display the data. Here's a simple example:

<!DOCTYPE html>
<html>
<head>
    <title>Task List</title>
</head>
<body>
    <h1>Task List</h1>
    <ul>
        {% for task in tasks %}
            <li>{{ task.title }} - {{ task.description }}</li>
        {% endfor %}
    </ul>
</body>
</html>
        

In this template, we use Jinja2 template tags to loop through the tasks and display their titles and descriptions.

Step 5: Running Your Application

As usual, run your Flask application with the following code at the end of your script:

if __name__ == '__main__':
    app.run()
        

Now, you can run your application with the command python your_app.py and access the '/tasks' route to view the data from the database.

Conclusion

Flask, SQLAlchemy, and HTML templates allow you to easily fetch data from a database and display it in your web applications. By creating routes, querying the database, and rendering data in your templates, you can build dynamic and data-driven web applications.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.