DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Resolving Parameter Sensitivity With Parameter Sensitive Plan Optimization in SQL Server 2022
  • Comparing Managed Postgres Options on The Azure Marketplace
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • SaaS in an Enterprise - An Implementation Roadmap
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Initialize Database With Default Values in SQLAlchemy Once After Database Creation

How to Initialize Database With Default Values in SQLAlchemy Once After Database Creation

Recently, while working on a Python app, I needed an SQLAlchemy functionality to insert default values into SQLite database. In particular, I simply needed to execute some DDL only once after the database was created. How does SQLAlchemy handle this? Let’s investigate it on a simple database model for a prototype of a todo app created in the online database designer Vertabelo.

By 
Patrycja Dybka user avatar
Patrycja Dybka
·
Feb. 25, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
43.3K Views

Join the DZone community and get the full member experience.

Join For Free

SQLAlchemy - events

Recently, while working on a Python app, I needed an SQLAlchemy functionality to insert default values into SQLite database. In particular, I simply needed to execute some DDL only once after the database was created.

How does SQLAlchemy handle this? Let’s investigate it on a simple database model for a prototype of a todo app created in the online database designer Vertabelo. 

Image title

The todo table stores basic information about task (title, description) and references priority table. This one stores three provided priorities (low, medium, high). 

Solution

Use after_create event from the event API

Subscribing to an event is possible through listen() function.

sqlalchemy - listen function


Or alternatively, the listens_for() decorator.

sqlalchemy - listen_for decorator


For my case, I can do it in two equivalent ways.

  1. Register a listener function for the table piority.
  2. def insert_initial_values(*args, **kwargs):
        db.session.add(Priority(name='low'))
        db.session.add(Priority(name='medium'))
        db.session.add(Priority(name='high'))
        db.session.commit()
    
    event.listen(Priority.__table__, 'after_create', insert_initial_values)
    
    or pass the SQL to execute into the DDL construct
    event.listen(Priority.__table__, 'after_create',
                DDL(""" INSERT INTO priority (id, name) VALUES (1, 'low'), (2, 'medium'), (3, 'high') """))
  3. Decorate the function as a listener with listens_for decorator.
  4. 
    @event.listens_for(Priority.__table__, 'after_create')
    def insert_initial_values(*args, **kwargs):
        db.session.add(Priority(name='low'))
        db.session.add(Priority(name='medium'))
        db.session.add(Priority(name='high'))
        db.session.commit()
    


Testing

For testing, I created a prototype application in Flask framework that uses plain SQLAlchemy models with the Flask-SQLAlchemy session.

The SQLAlchemy models were generated directly from the model designed in Vertabelo using script hosted on Github.

Here's the demo app (the code is also available on Github):


# models.py

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey, Unicode
from sqlalchemy.orm import relationship

Base = declarative_base()


class Todo (Base):
   __tablename__ = "todo"
   id = Column('id', Integer, primary_key = True)
   priority_id = Column('priority_id', Integer, ForeignKey('priority.id'))
   title = Column('title', Unicode)
   description = Column('description', Unicode)

   priority = relationship('Priority', foreign_keys=priority_id)


class Priority (Base):
   __tablename__ = "priority"
   id = Column('id', Integer, primary_key = True)
   name = Column('name', Unicode)


# app.py

from flask import Flask
from sqlalchemy.event import listen

from models import Todo, Priority, Base
from sqlalchemy import event, DDL
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.test'
db = SQLAlchemy(app)


# first solution
# @event.listens_for(Priority.__table__, 'after_create')
# def insert_initial_values(*args, **kwargs):
#     db.session.add(Priority(name='low'))
#     db.session.add(Priority(name='medium'))
#     db.session.add(Priority(name='high'))
#     db.session.commit()


# second solution
# def insert_initial_values(*args, **kwargs):
#     db.session.add(Priority(name='low'))
#     db.session.add(Priority(name='medium'))
#     db.session.add(Priority(name='high'))
#     db.session.commit()
#
#
# event.listen(Priority.__table__, 'after_create', insert_initial_values)

# third solution
event.listen(Priority.__table__, 'after_create',
            DDL(""" INSERT INTO priority (id, name) VALUES (1, 'low'), (2, 'medium'), (3, 'high') """))


@app.before_first_request
def setup():
   # Recreate database each time for demo
   Base.metadata.drop_all(bind=db.engine)
   Base.metadata.create_all(bind=db.engine)

   low_priority = db.session.query(Priority).filter_by(name=u'low').first()
   medium_priority = db.session.query(Priority).filter_by(name=u'medium').first()
   high_priority = db.session.query(Priority).filter_by(name=u'high').first()

   db.session.add(Todo(title=u'title1', description=u'description1', priority_id=low_priority.id))
   db.session.add(Todo(title=u'title2', description=u'description2', priority_id=medium_priority.id))
   db.session.add(Todo(title=u'title3', description=u'description3', priority_id=high_priority.id))
   db.session.commit()


@app.route('/')
def index():
   todos = db.session.query(Todo).join(Priority).all()

   return u"".join([u"{0}: {1}: {2}".format(todo.title, todo.description, todo.priority.name) for todo in todos])


if __name__ == '__main__':
   Base.metadata.create_all(bind=db.engine)
   app.run(debug=True)


Database

Opinions expressed by DZone contributors are their own.

Related

  • Resolving Parameter Sensitivity With Parameter Sensitive Plan Optimization in SQL Server 2022
  • Comparing Managed Postgres Options on The Azure Marketplace
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!