flask - Display database from python to html

后端 未结 3 1492
既然无缘
既然无缘 2021-02-01 09:40

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():
         


        
3条回答
  •  耶瑟儿~
    2021-02-01 09:44

    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--
    
    
            {% for row in output_data %} <-- Using these '{%' and '%}' we can write our python code -->
                
            {% endfor %}        <-- Because it is flask framework there would be other keywords like 'endfor'   -->
        
    ID Name Email Phone
    {{row[0]}} {{row[1]}} {{row[2]}} {{row[3]}}
    --snip--

    And finally you get expected result

提交回复
热议问题