D72 #100DaysOfCode

D72 #100DaysOfCode. I learned how to setup a databse using SQLAlchemy and get Flask to use it as well as creating some users and a post.

Read Time3 Minutes, 35 Seconds

It’s time to implement the database!

So following along with “The Flask Mega-Tutorial” I’m not learning how databases can be implemented into my Flask app.

So Flask does not have a specific Database that it requires which is great, it lets me decide on one, and in this case, it’s SQLite. The reason for SQLite is that it’s simple and easy to set up for a development environment.

I started by installing a couple of Python modules.

pip install flask-sqlalchemy

This is a great module for setting up a database in Python, it makes it so simple to add/remove users, as it can grab your classes and make them a table.

I have two classes User and Post, they can then be turned into tables.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    def __repr__(self):
        return '<User {}>'.format(self.username)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Post {}>'.format(self.body)

The user had a few basic values such as id which is the primary key, username, email, and password_hash, it also has a relationship with the Post class so I can pull data when needed.

The Post class has a primary key id, body which is used to store the content of the post and a timestamp. The timestamp has a default value so when a post is made a timestamp is automatically given to it. The user_id is pulled from the user class and is a foreign key.

The next module pulled is;

pip install flask-migrate

This is created by the author of the guide I’m following, it allows you to easily update your database when you have made changes.

When modules like this are installed you need to set them up in the config.py file.

import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False

You can see that SQL Alchemy needs to know where to find the database URL, I’ve set up a variable DATBASE_URL to tell SQL Alchemy where to find it if that fails it will look in the base directory for app.db.

Then editing my __init__.py file to setup some needed values.

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

Here I’m setting an SQLAlchemy object, which is my flask application, as well as setting migrate to the db and my flask app.

Now that it’s set up it brings me back to how classes become tables.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')

The user class inherits a base class from SQLAlchemy using db.Model.

Now using flask migrate I can set up my database.

Running flask db init creates a sub-directory in your working directory and gets you ready to create your database.

Once that’s set up we can run flask db migrate -m "users table" which prepares a script that will create this table, I guess it’s similar to a plan in Terraform. Makes sure everything is okay and gives you a chance to look at the script before running it.

Once you are happy you can run flask db upgrade and just like that it will create a db file if you don’t have one with your new table.

Now I’ll show you how easy it is to interact with that database.

0 0
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleppy
Sleppy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Leave a Reply

Your email address will not be published. Required fields are marked *

Close