Flask Seeder to generate test data

Data is a fundamental part of the system and when developing the application, it is always necessary to have test data to test each of the implemented modules of the application we are developing; creating this data manually is always tedious and when there is a lot of data or many entities for which we would have to create this test data it would be a nightmare; that's why modern frameworks like Flask provide a mechanism to generate this test data; inn the case of Flask, since it is a micro framework, we must install an additional package called Flask Seeder.

Flask-Seeder is a very simple package to use, it provides a Seeder base class that contains a database identifier and a run() method, where we obtain access to the object (model instance) to manipulate and create the data in the database. It also has a command to run the tests and some Faker-type methods that we can use to generate random data such as names and emails.

In reality, it would not be necessary to use this type of package, we could perfectly create a controller that together with a cycle generates some test data, but, using this package we can have a better modularization for the application apart from the fact that we have access to the Fake.

A Faker class looks like:

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

Where we have the components mentioned above present; to run the test:

$ flask seed run

All these classes are hosted in files and these are inside a folder called seeds/ and these classes must inherit from Seeder so that they can be detected by Flask Seeder.

You can see an example of how to generate test data using the generator:

# 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)

To install the package we have:

$ pip install Flask-Seeder

As for Fakers or false data generators, we have a few that we can use:

  • Integer: Create a random integer between two values
  • UUID: Create a random UUID
  • Sequence: Create integers in sequence if called multiple times
  • Name: Create a random name from a list of data/names/names.txt
  • Email: Create a random email, random name generator combination, and domain from data/domains/domains.txt
  • String: Generation of strings from a pattern.

Based on the application that we have been developing, we are going to generate test data for the categories and tags:

app\seeds\seed.py

from flask_seeder import Seeder, Faker, generator

from my_app.blog import models

class CategorySeeder(Seeder):

  # run() will be called by Flask-Seeder
  def run(self):
    # Create a new Faker and tell it how to create Category objects
    faker = Faker(
      cls=models.Category,
      init={
        "name": generator.Name(),
      }
    )

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

It is important to note that the seeds folder is located at the same level as the application module:

app\seeds\seed.py

And not inside:

app\my_app\seeds\seed.py

Since if you place it inside my_app, Flask Seeder will not recognize the seeds folder and therefore will not execute the seeders.

Finally, we execute the following command:

$ python -m flask seed run

Or

$ flask seed run

And we should see this data created in our database; you can run the previous command as many times as you want or need and vary the logic to your liking.

More information in:

https://pypi.org/project/Flask-Seeder/

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.