How to display database content in your flask website


File structure

Hi,I have a table called v_timestamp1 made in PostgreSQL. Lets see how we can display it in the Flask UI. First I m establishing connection with pgadmin in the try statement. Put your database name instead of silverTip, that is name of my database also my user is postgres, my password is sT789. Replace those with your specific credentials.Here is my code

from flask import Flask, request,render_template
import psycopg2
conn = psycopg2.connect(database="silverTip", user="postgres",
password="sT789", host="localhost")
print ("I am unable to connect to the database")
mycursor =conn.cursor()
app = Flask(__name__)

If you guys havent downloaded psycopg2, please do so before running the code, in the terminal. Please make sure you have made a database made in the postgreSQL.

pip install psycopg2

Code in index.html.In the body section I have just included a button, upon clicking that button lead to v_timestamp page.

<!DOCTYPE html>
<link rel="stylesheet" href="{{ url_for('static', filename='home.css') }}">


The index.html has the code for arrangement of styles for the main page( How the front page looks like in port 5000.

The code in the v_timestamp.html is given below. I have given the text alignment as center, and padding and border as specified in the code.My table column headings are vehicle ID, current timestamp, expiry timestamp.As specified under <th> element, those fonts appear in bold. The <tr> elements font is normal(not bold) .In the <td> elements, the instruction {{row[0]}} means to capture the first row details in the v_timestamp1 PostgrSQL db and so on. Do not get confused, v_timestamp1 is the db at postgreSQL. v_timestamp is the page I’m routing the main page upon a button click event.

<!DOCTYPE html>

td {
width: 150px;
text-align: center;
border: 1px solid black;
padding: 5px;
<th>vehicle ID</th>
<th>current timestamp</th>
<th>expiry timestamp</th>
{% for row in data %}
{% endfor %}

How the UI looks for v_timestamp page.

Thanks for reading. Have fun coding!!!

Student at University of Moratuwa