flask - Display database from python to html

Viewed 67255

I have code like this to retrieve data from database and I want to display it in html.

This is app.py

@app.route('/news')
def news():
    import pymysql
    import re

    host='localhost'
    user = 'root'
    password = ''
    db = 'skripsi'

    try:
        con = pymysql.connect(host=host,user=user,password=password,db=db, use_unicode=True, charset='utf8')
        print('+=========================+')
        print('|  CONNECTED TO DATABASE  |')
        print('+=========================+')
     except Exception as e:
        sys.exit('error',e)

     cur = con.cursor()
     cur.execute("SELECT * FROM dataset")
     data = cur.fetchall()

     for row in data:
         id_berita = row[0]
         judul = row[1]
         isi = row[2]
         print('===============================================')
         print('BERITA KE', id_berita)
         print('Judul :', judul)
         print('Isi   :', isi)
         print('===============================================')

return render_template('home.html')

This is the result

enter image description here

This is berita.html. I want to display inside div class = output

<body>
<center>
<header style="padding-top: 10px; font-family: Calibri; font-size: 40pt;">WELCOME!</header><br>
<div class="nav">
  <a href="/home">Home
  <a href="/berita">Berita
  <a href="/preprocessing">Pre-Processing
  <a href="/feature">Fitur Ekstraksi
  <a href="/knn">KNN
</div>
<div class="output">
</div>

3 Answers

Suppose you have table_name = user_info and let's visualize it:

id| name | email | phone | 1 | Eltac | eltac@gmail.com | +99421112 |


You can do something like this:

app_name.py

from flask import Flask, render_template
import mysql.connector

mydatabase = mysql.connector.connect(
    host = 'localhost(or any other host)', user = 'name_of_user',
    passwd = 'db_password', database = 'database_name')


mycursor = mydatabase.cursor()

#There you can add home page and others. It is completely depends on you

@app.route('/example.html')
def example():
   mycursor.execute('SELECT * FROM user_info')
   data = mycursor.fetchall()
   return render_template('example.html', output_data = data)


In the above code we use fetchall() method that's why ID is also included automatically

(Header html tag and others are ignored. I write only inside of body) example.html

--snip--

<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    </thead>
    <tbody>
        {% for row in output_data %} <-- Using these '{%' and '%}' we can write our python code -->
            <tr>
                <td>{{row[0]}}</td>
                <td>{{row[1]}}</td>
                <td>{{row[2]}}</td>
                <td>{{row[3]}}</td>
            </tr>
        {% endfor %}        <-- Because it is flask framework there would be other keywords like 'endfor'   -->
    </tbody>
</table>

--snip--


And finally you get expected result

Related