网页显示数据库信息
使用我们刚学习的flask_sqlalchemy,在网页中显示数据库表中的数据。
在开始运行程序前,确保数据库中执行过创建表和创建用户的操作,详见链接描述。
# 模板文件templates/list.html
{% extends 'base.html' %}
{% block title %}
显示
{% endblock %}
{% block newcontent %}
<table class="table table-striped">
<tr>
<th>用户编号</th>
<th>用户名称</th>
<th>用户密码</th>
<th>用户创建时间</th>
<th>用户会员类型</th>
</tr>
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.passwd }}</td>
<td>{{ user.add_time }}</td>
<td>{{ user.role.name }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
# 数据库操作文件zaj_sql_models.py
from datetime import datetime
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import pymysql
from sqlalchemy import desc
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:sheen@localhost/zaj_sql'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
bootstrap = Bootstrap(app)
# class Student(db.Model):
# __tablename__ = 'students'
# sid = db.Column(db.SMALLINT,primary_key=True)
# sname = db.Column(db.String(50))
# sage = db.Column(db.Integer)
class User(db.Model):
id = db.Column(db.Integer,autoincrement=True,primary_key=True)
name = db.Column(db.String(50),unique=True)
passwd = db.Column(db.String(100))
add_time = db.Column(db.DATETIME,default=datetime.now())
gender = db.Column(db.BOOLEAN,default=True)
role_id = db.Column(db.INTEGER,db.ForeignKey('role.id'))
def __repr__(self):
return '<User:%s>' %(self.name)
class Role(db.Model):
id = db.Column(db.INTEGER,autoincrement=True,primary_key=True)
name = db.Column(db.String(50),unique=True)
users = db.relationship('User',backref='role')
# 给Role模型添加users属性
# backref 是定义反向引用,可以通过User.role访问User里面的数据
def __repr__(self):
return '<Role:%s>' % (self.name)
if __name__ =='__main__':
# 1. 创建数据库表
db.drop_all()
db.create_all()
# 2. 创建role数据库表数据
role_1 = Role(name='超级会员')
role_2 = Role(name='普通会员')
db.session.add(role_1)
db.session.add(role_2)
db.session.commit()
# # # 3. 添加user表内数据,100个用户,50个为超级会员,50个为普通会员
for i in range(1,13):
if i%2 == 0:
u = User(name='sheen'+str(i),passwd='sheen',role_id=1)
db.session.add(u)
else:
u = User(name='star'+str(i),passwd='star',role_id=2)
db.session.add(u)
db.session.commit()
#主程序
from flask import Flask,render_template
from zaj_sql_models import app
from zaj_sql_models import User
@app.route('/')
def index():
return render_template('index.html')
@app.route('/list/')
def list():
users = User.query.all()
return render_template('list.html',users=users)
if __name__ == '__main__':
app.run()