How to Insert Dummy Data into Databases using Flask
Last Updated :
26 Apr, 2025
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:
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
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
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):
for data in seed_data:
user_obj = User( * data)
user_obj.create()
print ( "Successfully Added" )
def print_all_data():
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 ):
|
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
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:

Similar Reads
How to import CSV file in SQLite database using Python ?
In this article, we'll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students. Approach: Importing necessary modulesRead data from CSV file DictRead
2 min read
How to create a new project in Django using Firebase Database?
Django is a Python-based web framework that allows you to quickly create efficient web applications. If you are new to Django then you can refer to Django Introduction and Installation. Here we are going to learn How to create a Django project using Firebase as Database . How to create a new project
3 min read
Get the id after INSERT into MySQL database using Python
Prerequisites: MySQL, mysql-connector for python The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The
2 min read
How to store XML data into a MySQL database using Python?
In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database. RequirementsXAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It i
3 min read
How to Run Django's Test Using In-Memory Database
By default, Django creates a test database in the file system, but it's possible to run tests using an in-memory database, which can make our tests faster because it avoids disk I/O operations. In this article, weâll explore how to run Django tests with an in-memory database, the advantages of this
6 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect()
3 min read
Store Google Sheets data into SQLite Database using Python
In this article, we are going to store google sheets data into a database using python. The first step is to enable the API and to create the credentials, so let's get stared. Enabling the APIs and creating the credentialsGo to Marketplace in Cloud Console.Click on ENABLE APIS AND SERVICESThen Searc
5 min read
How to Build a Web App using Flask and SQLite in Python
Flask is a lightweight Python web framework with minimal dependencies. It lets you build applications using Python libraries as needed. In this article, we'll create a Flask app that takes user input through a form and displays it on another page using SQLite. Run the following commands to install F
3 min read
Making a Flask app using a PostgreSQL database
The Postgres database can be accessed via one of two methods in Python. Installing PgAdmin4 is the first step because it offers a user interface for interacting with databases and another for using the psycopg2 connector. In this post, we'll concentrate on a different approach that lets us alter the
4 min read
How to take backup of MySQL database using Python?
In this article, we are going to learn how to back up a MySQL database using python. Database used: Python modules required: In this post, we are going to use the mysql-connector module of python to back up our data. You can install mysql-connector with the following command: pip install mysql-conne
3 min read