Skip to content

A simple Flask app that introduces SQLAlchemy and models

License

Notifications You must be signed in to change notification settings

ChristinaVoss/flask-models

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Flask models

App structure

Now that we have several "moving parts", I have made this app fairly simple, with form, model and controller (@route) in app.py. In a real app consider moving the model into its own models.py file (or even have separate models.py files for each part of the application, as demonstrated in flask-blueprints.

Screenshot 2022-05-12 at 09 39 07

Key parts

In app.py:

Import your installed libraries related to database and migrations:

from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

Configure your database (set data path etc), and define a variable to use for your database queries (db):

basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
Migrate(app, db)

Define your database table (called model, though defined as a Python class and inherits from db.Model). Include an __init__() method to initialise your objects and and a __repr__() method to give your bojects a string representation (so you can print them...):

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    # initialise an instance (row) of a table/entity
    def __init__(self, email, name):
        self.email = email
        self.name = name

    def __repr__(self):
        return '<User %r>' % self.username

At the bottom of your model definitions (if you have more than one), add this line to create the tables:

db.create_all()

You can now create a user in @app.route('/'):

user = User(email=form.email.data,
            name = form.name.data)

# To add a row to the User table in the database:
db.session.add(user)
db.session.commit()

And query the database as seen in @app.route('/users'):

users_list = User.query.all()

Setup

If you have not installed Python3, please do.

First create and activate some form of environment to store your dependencies. I like Conda:

$ conda create -n myenv python=3.7

$ conda activate myenv

Or just use Pythons built in environments:

$ python3 -m venv venv

$ . venv/bin/activate

Then install Flask, Flask-SQLAlchemy, Flask-Migrate, and also WTForms (because we added a form to update the database).

$ pip install Flask Flask-WTF Flask-SQLAlchemy Flask-Migrate

Run the app

$ flask run

You should now be able to see the output in your browser window (at http://127.0.0.1:5000)

Resulting pages

index.html

Screenshot 2022-05-12 at 18 05 26

users.html

Screenshot 2022-05-12 at 18 05 47