• python flask 如何读取数据库数据并返回到html


    app.py

    from flask import Flask
    from flask import render_template
    from flask_bootstrap import Bootstrap
    import pymysql
    app = Flask(__name__)
    bootstrap = Bootstrap(app)
    
    @app.route('/')
    def index():
        conn = pymysql.connect(host='*.*.*.*', user='root', password='root', db='mydb', charset='utf8')
        cur = conn.cursor()
        sql = "SELECT * FROM user"
        cur.execute(sql)
        u = cur.fetchall()
        conn.close()
        return render_template('index.html',u=u)
    if __name__ == '__main__':
        app.run()

    base.html

    {% extends "bootstrap/base.html"  %}
    {% block title %}Flask{% endblock %}
    {% block navbar %}
    <div class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/">PMSystem</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="/">首页</a></li>
                </ul>
            </div>
        </div>
    </div>
    {% endblock %}
    
    {% block content %}
    <div class="container">
      {% block page_content %}{% endblock %}
    </div>
    {% endblock %}

    index.html

    {% extends "base.html" %}
    
    {% block title %}首页{% endblock %}
    
    {% block page_content %}
        <table class="table table-bordered">
        <tr>
            <th>用户ID</th>
            <th>公司ID</th>
            <th>公司名称</th>
            <th>联系电话</th>
            <th>联系邮箱</th>
            <th>用户姓名</th>
            <th>所属公司</th>
        </tr>
            {% for i in u %}
                <tr>
                    <td>{{ i[0] }}</td>
                    <td>{{ i[1] }}</td>
                    <td>{{ i[2] }}</td>
                    <td>{{ i[3] }}</td>
                    <td>{{ i[4] }}</td>
                    <td>{{ i[5] }}</td>
                    <td>{{ i[6] }}</td>
                </tr>
        {% endfor %}
        </table>
    
    {% endblock %}

    结果:

     

    转载:https://www.cnblogs.com/zhouwp/p/8243738.html

  • 相关阅读:
    OAuth2在微服务架构中的应用
    使用SpringSecurity体验OAuth2 (入门2)
    SpringSecurity的配置分析
    SpringSecurity在Springboot下使用的初步体验
    Spring框架中的org.springframework.context.annotation.Import注解类
    使用SpringSecurity体验OAUTH2之一 (入门1)
    5. SpringBoot —— Actuator简介
    无题
    C# 委托的本质
    json 字符串 反序列化
  • 原文地址:https://www.cnblogs.com/wt869054461/p/15911251.html
Copyright © 2020-2023  润新知