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 # 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
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 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 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 projec
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 insert request body into a MySQL database using Express js
If you trying to make an API with MySQL and Express JS to insert some data into the database, your search comes to an end. In this article, you are going to explore - how you can insert the request data into MySQL database with a simple Express JS app. Table of Content What is Express JS?What is MyS
3 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
Sending Data from a Flask app to MongoDB Database
This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use. MongoDB is an open-source database that stores data
5 min read