Skip to content Skip to sidebar Skip to footer

Flask - Display Database From Python To Html

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='lo

Solution 1:

You can pass your data using render_template() like this:

cur = con.cursor()
cur.execute("SELECT * FROM dataset")
data = cur.fetchall()
render_template('template.html', data=data)

Then in your template, iterate over the rows, for example you could render table rows for each row:

{% for item in data %}
<tr>
    <td>{{item[0]}}</td>
    <td>{{item[1]}}</td>
    ...
</tr>
{% endfor %}

Solution 2:

render_template allows you to pass variables to html, and jinja2 help you to manipulate it. You only need to format your query result and send it within render_template

Example

app.py

@app.route('/test')
def test_route():
    user_details = {
        'name': 'John',
        'email': 'john@doe.com'
    }

    return render_template('test.html', user=user_details)

test.html

<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <!-- use {{}} to access the render_template vars-->
        <p>{{user.name}}</p>
        <p>{{user.email}}</p>
    </body>
</html>

to make the most of jinja2, take a look at his Documentation


Solution 3:

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


Post a Comment for "Flask - Display Database From Python To Html"