简体   繁体   中英

What is the best way to populate a table in SQLAlchemy?

I'm trying to create a list of possible roles of a web app user. If I define the roles table in this way:

roles = db.Table(
    "roles",
    db.Model.metadata,
    db.Column("role_id", db.Integer, db.ForeignKey("task.id"), primary_key=True),
    db.Column("name", db.String(32)),
)

What is the best method to populate it if I intend to only do that once (on database creation), and then never add any more rows to it?

I believe this paradigm is called "database seeding", this might help you when you are googling for answers.

I had a look online and found this: https://pypi.org/project/Flask-Seeder/

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_seeder import FlaskSeeder

    def create_app():
      app = Flask(__name__)

      db = SQLAlchemy()
      db.init_app(app)

      seeder = FlaskSeeder()
      seeder.init_app(app, db)

      return app

Then you can create a another file with your seeds.

    from flask_seeder import Seeder, Faker, generator

    # SQLAlchemy database model
    class User(Base):
      def __init__(self, id_num=None, name=None, age=None):
        self.id_num = id_num
        self.name = name
        self.age = age

      def __str__(self):
        return "ID=%d, Name=%s, Age=%d" % (self.id_num, self.name, self.age)

    # All seeders inherit from Seeder
    class DemoSeeder(Seeder):

      # run() will be called by Flask-Seeder
      def run(self):
        # Create a new Faker and tell it how to create User objects
        faker = Faker(
          cls=User,
          init={
            "id_num": generator.Sequence(),
            "name": generator.Name(),
            "age": generator.Integer(start=20, end=100)
          }
        )

        # Create 5 users
        for user in faker.create(5):
          print("Adding user: %s" % user)
          self.db.session.add(user)

And finally, you can call

$ flask seed run

to populate the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM