[python] Flask SQLAlchemy insert data

On previous post it was demonstrated that creating database is easier with Flask SQLAlchemy than using SQLAlchemy itself.
This post demonstrates how data can be inserted to existing database, and also to check if the tables exist before executing create_all(). create_all() does not re-create table if the table exists, the if statement is to demonstrate how the existence of the table can be checked using the db object created from SQLAlchemy(app).

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import date


app = Flask(__name__)

# The same can be done this way:
# app.config['SQLALCHEMY_DATABASE_URI'] = your DB connection string
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config.from_pyfile('config.py')

# pass in the app into SQLAlchemy to create a db session.
db = SQLAlchemy(app)

# declare the class for the model.
class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Members(db.Model):
    # the id does not need to add value as it is auto incrementing because it is primary key
    # each column is a position, you will need to specify username=. password= and date_joined=
    # for each db insertion.
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(60), unique=True)
    password = db.Column(db.String(60))
    date_joined = db.Column(db.DateTime)

if __name__ == '__main__':
    # The creation starts here.
    # the same can be done by creating an create_engine object.
    # example:
    # from sqlalchemy import create_engine
    # engine = create_engine()
    # if not engine.has_table(tablename)
    if not (db.engine.has_table('members') and db.engine.has_table('test')):
        db.create_all()

    # inserting new information about Members
    # A new member name John
    john = Members(username='John', password='abcd123', date_joined=date.today())
    db.session.add(john)
    db.session.commit()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s