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 Postgres database: using the psycopg2 connector. This article presupposes that Postgres has been successfully installed on your computer or device.
Let’s get started on the project. An HTML page will be added to display the modifications, along with a few products and their prices. It will include the three tables. earliest for product details. second to update existing items, and third to add new ones.
Steps to make Flask app using a PostgreSQL Database
Step 1: Open your command line tool and connect with Postgres. After entering the username it will ask you for the password enter it appropriately.
psql -U username
Step 2: Once we successfully connected then create a new database ‘flask_db’. We will use it further to create tables in it.
Step 3: Create a folder structure like this.
Step 4: Connect with the database. you will have to use psycopg2 connect to use the commands.
Step 5: app.py
This will authenticate the user and allows us to execute queries on it. It creates a cursor on the connection by using cur. execute() method executes the queries for us. Once we completed our queries we have to close the connection for security purposes.
Step 4: templates/index.html
You will need this index file to see results and perform operations. Just add these template codes to their respective path.
Step 4: Run our app
Enter the flask run command to run it in the development mode and make sure the flask debug is on.
Through this, we have successfully executed Crud operations on the database. You will have the output attached to this and a GitHub repository link where you can find all the source code.
Please Login to comment...