在实际工作中,前后端数据交互大部分都是用的json格式,后端把数据处理完后,把json传给前端,前端再解析
项目结构
models里面加入把数据转为字典的方法
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Department(db.Model):
""" 部门 """
__tablename__ = 'department'
# primary_key=True:主键, autoincrement=True:自动递增
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), unique=True)
def __init__(self, name):
self.name = name
def __repr__(self):
return f'部门{self.id},{self.name}'
def to_json(self):
""" 用于后面把SQLAlchemy的内容转成json对象 """
return dict(id=self.id, name=self.name)
class Employee(db.Model):
""" 员工 """
__tablename__ = 'employee'
# primary_key=True:主键, autoincrement=True:自动递增
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
gender = db.Column(db.String)
job = db.Column(db.String)
birthdate = db.Column(db.Date)
idcard = db.Column(db.String)
address = db.Column(db.String)
salary = db.Column(db.Float)
release_time = db.Column(db.DateTime)
# 外键: db.Column(db.Integer, db.ForeignKey(表名))
department_id = db.Column(db.Integer, db.ForeignKey('department.id')) # 声明是外键,为department表的id字段
# db.relationship('Department', backref=db.backref('employee', lazy='dynamic'))
# db.relationship(主键类名, backref=引用属性名, lazy='dynamic'))
# lazy:延迟查询:dynamic:动态、select、subquery、joined
department = db.relationship('Department', backref=db.backref('employee', lazy='dynamic')) # 类与表的关系
def __init__(self, name=None, gender=None, job=None, birthdate=None, idcard=None, address=None, salary=None,
release_time=None):
self.name = name
self.gender = gender
self.job = job
self.birthdate = birthdate
self.idcard = idcard
self.address = address
self.salary = salary
self.release_time = release_time if release_time else datetime.now()
def __repr__(self):
return f'员工:{self.id} {self.name} {self.salary} {self.address}'
def to_json(self):
""" 用于后面把SQLAlchemy的内容转成json对象 """
return dict(id=self.id, name=self.name, address=self.address, salary=self.salary)
if __name__ == '__main__':
db.create_all()
emp-json.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>josn数据</title>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
部门:<select name="部门" id="department"></select>
姓名:<input type="text" id="name">
<input type="button" value="点击查询" id="btnSearch">
<div id="emp-list"></div>
</body>
</html>
<script>
$(document).ready(function () {
// 页面准备好之后就把部门的信息查出来,并渲染到部门的下拉列表里面
$.ajax({
url: '/department/',
method: 'GET',
dataType: 'json',
success: function (depts) {
$.each(depts, function (i, item) {
$('#department').append('<option value="' + item.id + '">' + item.name + '</option>');
});
}
});
// 查询按钮点击事件
$('#btnSearch').click(function () {
var dept_id = $('#department').val();
var name = $('#name').val();
$.ajax({
url: '/emp-info/',
method: 'GET',
data: {'name': name, 'department': dept_id},
success: function (datas) {
$('#emp-list').html(''); // 清空id为emp-list下的内容,防止重复渲染
// 如果后端返回来的状态是0,即有数据,就进行数据解析渲染
if (datas['status']==0) {
var table_header = '<table border="1"><tr><th>ID</th><th>姓名</th><th>地址</th><th>工资</th></tr>';
var rows = "";
$.each(datas['datas'], function (i, data) {
rows += '<tr><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.address + '</td><td>' + data.salary + '</td></tr>';
$('#emp-list').html(table_header + rows + '</table>');
});
}
}
});
});
});
</script>
main.py
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from personal.models import Employee, Department
app = Flask(__name__, static_url_path='')
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./db/test.db' # 声明数据库类型和地址
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 跟踪改变
# app.config['SQLALCHEMY_ECHO'] = True # 打印对应的sql,此操作用sql是怎么样的
# 返回部门信息
@app.route('/department/')
def get_department():
""" 单个的情况
dept = Department.query.first()
return jsonify(dept.to_json())
"""
# 多个的情况
depts = Department.query.all()
return jsonify([d.to_json() for d in depts])
@app.route('/emp-info/')
def emp_info():
"""
1、从地址栏获取要查询的的部门好好员工名
2、根据部门和员工名,获取员工信息
3、返回json格式的信息
"""
name = request.args.get('name', '')
dept = request.args.get('department', '')
# datas = db.session.query(Employee).filter(Employee.name == name, Employee.department_id == dept)
datas = db.session.query(Employee).filter(Employee.name == name).filter(Employee.department_id == dept)
if datas:
return jsonify({
'status': 0,
'datas': [d.to_json() for d in datas]
})
return jsonify({
'status': 1,
'datas': []
})
@app.route('/emp-json/')
def emp_json():
return render_template('emp-json.html')
if __name__ == '__main__':
app.run(debug=True)
数据信息:
访问
有效数据
无效数据,会清空内容,并不渲染