How to load source data into a database using sqlalchemy

I want to be able to load data automatically when creating tables using SQLAlchemy.

In django, you have fixtures that let you easily pre-populate a database with data when creating a table. It seemed to me useful, especially when you have basic search tables, for example product_type, student_type, which contain only a few rows, or even a currency type table that will load all the currencies of the world without having to enter them again and again when you destroy your models / classes.

My current application does not use Django. I have SQLAlchemy. How can I achieve the same? I want the application to know that the database is being created for the first time, and therefore it populates some tables with data.

+5
source share
2 answers

I used an event listener to pre-populate the database with data when creating the table.

Let's say you have a ProductType model in your code:

 from sqlalchemy import event, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class ProductType(Base): __tablename__ = 'product_type' id = Column(Integer, primary_key=True) name = Column(String(100)) 

First, you need to define a callback function that will be executed when the table is created:

 def insert_data(target, connection, **kw): connection.execute(target.insert(), {'id': 1, 'name':'spam'}, {'id':2, 'name': 'eggs'}) 

Then you just add an event listener:

 event.listen(ProductType.__table__, 'after_create', insert_data) 
+3
source

The short answer is no, SQLAlchemy does not provide the same function as dumpdata and loaddata like Django.

There is https://github.com/kvesteri/sqlalchemy-fixtures , which may be useful for you, but the workflow is different.

+1
source

Source: https://habr.com/ru/post/1489606/


All Articles