Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Run Django's Test Using In-Memory Database
Next article icon

How to Insert Dummy Data into Databases using Flask

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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
 

Next Article
How to Run Django's Test Using In-Memory Database

A

akshitaggarwal04081999
Improve
Article Tags :
  • Python
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences