Flask app using Models

We create a simple flask app named “eventLog” where you can see and add events. The date and time are added automatically when the event is added. It just contains a single home page.

File structure

rootFolder
|_ eventLog
    |_templates
    |   |_ home.html
    |_ __init__.py

__init__.py File

This is a Flask web application with a SQLite database for managing events. It defines a “create_app” function setting up the Flask app, SQLAlchemy for database handling, and a simple “Event” model. The code includes a route for rendering and handling form submissions on the home page to add events to the database. Additionally, it has a CLI command “init-db” to initialize the database.

Python3




from flask import Flask, redirect, url_for, render_template, request
import os
import datetime
 
import click
 
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
 
def create_app(test_config=None):
    # a simple page that says hello
    app = Flask(__name__, instance_relative_config=True)
 
    app.config.from_pyfile('config.py', silent=True)
    app.config.from_mapping(SECRET_KEY='dev')
 
    # ensure instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass
 
    # configure the path to SQLite database, relative to the app instance folder
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///event_database.db"
 
    class Base(DeclarativeBase):
        pass
 
    # create the database object and initiate it
    db = SQLAlchemy(model_class=Base)
    db.init_app(app)
 
    # defining model for event
    class Event(db.Model):
        date = mapped_column(db.String, primary_key=True)
        event = mapped_column(db.String)
 
    @click.command('init-db')
    def init_db_command():
        ''' command for initiating the database '''
        with app.app_context():
            db.create_all()
            click.echo('Database created successfully')
 
    app.cli.add_command(init_db_command)
 
    @app.route('/', methods=['GET', 'POST'])
    def home():
        if(request.method == 'POST'):
            db.session.add(Event(date=datetime.datetime.now(
            ).__str__(), event=request.form['eventBox']))
            db.session.commit()
            return redirect(url_for('home'))
        return render_template('home.html', eventsList=db.session.execute(db.select(Event).order_by(Event.date)).scalars())
 
    return app


home.html Jinja Template

This HTML code defines a simple webpage displaying an event log with a table showing date-time and event details. It uses Jinja2 templating to iterate through a list of events passed from the Flask app and dynamically populate the table rows. The page also includes a form to add new events, with a text input and a submit button. Additionally, it links to an external stylesheet named “style.css” for styling.

HTML




<html>
    <head>
        <title>EventLog</title>
        <link rel = 'stylesheet' href = {{url_for('static', filename='style.css')}}/>
    </head>
    <body>
        <table>
            <tr>
                <th>Date & Time</th>
                <th>Event Details</th>
            </tr>
        {%-for row in eventsList-%}
            <tr>
                <td>{{row.date}}</td>
                <td>{{row.event}}</td>
            </tr>
        {%-endfor-%}
        </table>
        <hr/>
        <form method="post">
            <title>Add event</title>
            <label for="eventBox">Event Description</label>
            <input name="eventBox" id="eventBox" required/>
            <input type="submit" value = "Add">
        </form>
    </body>
</html>


Output

A simple flask app “eventLog” running on browser. Uses Flask Models for managing database.

Running the app

First run the following command from the rootFolder to initiate the database –

flask --app eventLog init-db

Once done, run the flask app using the command –

flask --app eventLog run --debug

This will start the app in debug mode at local host port 5000. Visit the following URL in browser –

http://127.0.0.1:5000/

Video Output

Declaring Models in Flask

Models are used in Flask to conveniently handle interactions with databases (like SQL, SQLite, etc.) using ORM (Object Relational Mapping). This article describes what is ORM, how to declare models in Flask, and finally a simple example Flask application. It assumes basic familiarity with Flask and Python programming languages.

Similar Reads

What is ORM in Python Flask?

ORM (Object Relational Mapping) is a programming technique which lets the programmer to write code using the Object-Oriented features of a language to interact with a database....

Declaring Models in Flask

The Flask community provides the “Flask-SQL Alchemy” library/extension which is the go-to library for declaring models in Flask. It is a wrapper around the “SQL Alchemy” library with added capabilities to handle the details related to responses and requests so that you don’t have to worry about that. Before proceeding any further, we need to have the following installations –...

Declaring Models in Flask with Flask-SQL Alchemy

This section contains the step-by-step explanation of the code. After doing the necessary imports, we define the create_app function which returns the flask app (the app-factory method of creating flask apps). We create the app and define everything inside this function since this app is small. If it is large, then in-practice, one would generally create multi-file definitions and then add them to the app inside this function by using flask features such as blueprints. Here is the explanation of the code inside this function –...

Flask app using Models

...

Conclusion

...

Contact Us