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

文件结构目录如下

python flask 如何读取数据库数据并返回到html_第1张图片

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='127.0.0.1', user='root', password='root', db='database', 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(host='0.0.0.0',debug=True)
# 这会让操作系统监听所有公网IP
#若果使用了Flask-Script的话,上面的操作会有问题,这时需要在runserver的那个py文件里,比较美观合适的位置加上:
#manager.add_command('runserver', Server(host='0.0.0.0'))
复制代码

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 navigationspan>
                <span class="icon-bar">span>
                <span class="icon-bar">span>
                <span class="icon-bar">span>
            button>
            <a class="navbar-brand" href="/">PMSystema>
        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>用户IDth>
        <th>公司IDth>
        <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 %}
复制代码

结果:

python flask 如何读取数据库数据并返回到html_第2张图片

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

你可能感兴趣的:(python2.7)