Monday, November 18, 2024
Google search engine
HomeLanguagesHow to Insert Dummy Data into Databases using Flask

How to Insert Dummy Data into Databases using Flask

Dummy data addition is a crucial component of development, particularly when you are just building up your project. Although adding dummy data to your database might be highly annoying, doing so is absolutely necessary to speed up your development process. The sample code for Flask to insert dummy data into the database is shown in this article using Python. we’ll be presenting this in our personal setup using PostgreSQL (RDBMS). We will define a function to add three entries to the user data table with the appropriate folder structure as an example.

Project Setup and Project folder

  • First, we need to initialize our Flask Application and install dependencies.
  • To initialize your application, create a virtual environment to avoid any compatibility issues related to the version of the packages.
  • Once your virtual environment is setup then install Flask and another dependency, via pip install
  • Create this project folder structure in your repo like this:
How to Insert Dummy Data into Databases using Flask

 

Step 1: Configure the APP with SQLAlchemy

For the app/__init__.py file, Add the following code in __init__.py, which is the configuration of our project

Python3




from app import models
from flask import Flask
# flask_sqlalchemy is an ORM For Databases
from flask_sqlalchemy import SQLAlchemy
# flask_migrate is to manage migration of files
from flask_migrate import Migrate
  
# our flask app
app = Flask(__name__, instance_relative_config=True)  
app.config.from_object('config.Config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)


Step 2: Creating User Schema

For app/models/user.py, add the following Class Schema for our user_data table. The below snippet defines the schema for the user_data table, have properties and functions. 

  • create() function in the class handles the functionality of adding rows to the table. 
  • print_all_user()  function return all row in the user_data table.

Python3




from app import db
  
  
class User(db.Model):
    __tablename__ = 'user_data'
  
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(20))
    last_name = db.Column(db.String(20))
    address = db.Column(db.String(200))
  
    def __init__(self, first_name: str, last_name: str, address: str):
        self.first_name = first_name
        self.last_name = last_name
        self.address = address
  
    def create(self):
        new_user = User(self.first_name, self.last_name, self.address)
        db.session.add(new_user)
        db.session.commit()
  
    @staticmethod
    def print_all_user():
        user_data = User.query.all()
        return user_data


In app/models/__init__.py, import the User Schema which is defined in the above snipped.

Python3




from app.models.user import User


Step 3: Creating Dummy Data which we want to insert

In app/data.py have our dummy data which needs to be inserted into the DB.

Python3




dummy_data  = [
    ("First_name_1", "Second_name_2", "ABC_1 City, XYZ_1 Town"),
    ("First_name_2", "Second_name_2", "ABC_1 City, XYZ_2 Town"),
    ("First_name_3", "Second_name_3", "ABC_1 City, XYZ_3 Town"),
]


Step 4: Defining Functions to Push Data into DB

app/helper.py have the main logic to add and print data, UserHelper class has two function

  • add_dummy_user_data – which takes input as seed_data and inserts it into the DB.
  • print_all_data – which fetches all records from the database

Python3




from app.models import User
  
  
class UserHelper:
    def add_dummy_user_data(seed_data):
        '''
        Function to add dummy user data into Table
        arg : seed_data which is list of 
        user info which we want to add
        '''
        for data in seed_data:
            user_obj = User(*data)
            user_obj.create()
        print("Successfully Added")
  
    def print_all_data():
        '''
        Function to print user data available in DB
        '''
        user_list = User.print_all_user()
        for user in user_list:
            print(
                f"User Name : {user.first_name}  {user.last_name} , 
              Address : {user.address}")
        if len(user_list) == 0:
            print("No Record Found")


Step 5: Creating and Initializing Postgres Database

Initialize config.py outside the app folder. For the initial configurations, Create a database. Please refer to this step for a nicely written article on GFG https://www.geeksforgeeks.org/postgresql-create-database/. For connecting DB with the application, we need a config file where we define the Database URI(where your database is running).  

Python3




import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
    SQLALCHEMY_DATABASE_URI = "postgresql://postgres:password@localhost:5432/db_name"


Step 6: Making Migrations in the database

We need to first create our user_data table first, to do so run the following command on your terminal in the order given below:

  • flask db init: this will initialize the migration folder into your project
  • flask db migrate: this will create migration files 
  • flask db upgrade: this will push the changes into the database

This will create an empty user_data table in your database.

flask db init
flask db migrate
flask db upgrade

Step 7: Calling  Function to push data into DB

Once everything is ready, We can call this add_dummy_user_data function to insert dummy data either by exposing an API (which is not recommended over the Production Database as this may lead to inconsistency in the Production Database) or through Shell.

We will be covering inserting data through Shell in this article, to call this function through CLI,  run flask shell in your project folder. Import UserHelper class and dummy_data into the shell by executing the below lines.

flask shell
>>> from app.helper import UserHelper
>>> from app.data import dummy_data
How to Insert Dummy Data into Databases using Flask

 

Execute the below command and your data will be inserted.

UserHelper.add_dummy_user_data(dummy_data)

To check all rows in the Database, execute the below line

UserHelper.print_all_data()

Output:

How to Insert Dummy Data into Databases using Flask

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments