I want to create a dynamic HTML page with the values from the PostgresQL database applied in necessary position of the HTML template.
The below image is a part of HTML page, i want that areas to be filled from the values from the database,Is there a way to do that? or is there any other better way to do that.
Im using Python and PostgreSQL database.
Thanks in Advance
import psycopg2
import jinja2
from collections import namedtuple
TEMPLATE="""
<!DOCTYPE html>
<html><head><title>Jinja Template Example</title>
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet" media="screen">
<style type="text/css">
.container {max-width: 500px;padding-top: 100px;}</style></head>
<body>
<div class="container">
<p>My string: {{my_string}}</p>
<p>Value from the list:</p>
<p>Loop through the list:</p>
<p style="line-height: 14px; text-align: center; font-size: 12px; margin: 0;"> Database Value </p><br>
<p style="line-height: 14px;font-weight:Bold; text-align: center; font-size: 12px; margin: 0;">Database value</p>
<ul>
{% for row in test_records %}
<li>{{ test_records.column1 }}</li>
{% endfor %}
</ul>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js">
</script>
<script src="http://netdna.bootstrapcdn.com/bootstr
ap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
"""
def dB_Fetch():
try:
connection = psycopg2.connect(user="sandeep",
password="postgres",
host="127.0.0.1",
port="5432",
database="postgres")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from test"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from test table using cursor.fetchall")
test_records = cursor.fetchall()
a = list();
print("Print each row and it's columns values")
for row in test_records:
a.append(test_records);
#print("column1 = ", row[0] )
#print("column2 = ", row[1])
print(a[0])
env = jinja2.Environment()
template = env.from_string(TEMPLATE)
row_tuple = namedtuple("Row", [col[0] for col in cursor.description])
result = template.render(rows=[row_tuple(row) for row in cursor.fetchall()])
print (TEMPLATE)
print (result)
except (Exception, psycopg2.Error) as error:
print ("Error while fetching data from PostgreSQL", error)
finally:
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
if __name__ == '__main__':
dB_Fetch()
enter code here
