测开之路一百四十五:SQLAlchemy与后台模板整合之新增、查询、删除
实现在页面上点击展示页就展示内容,点击新增页就触发新增功能
项目结构
admin.__init__
from flask import Blueprint
admin = Blueprint('admin', __name__) # 声明蓝图
# 把蓝图下的视图导进来注册到蓝图
from admin.views import *
admin.add_url_rule('/emp-list/', view_func=EmployeelListView.as_view('emp_list')) # 展示接口
admin.add_url_rule('/emp-del/<int:id>/', view_func=EmployeelDeleteView.as_view('emp_del')) # 删除接口
admin.add_url_rule('/emp-create/', view_func=EmployeeCreateView.as_view('creat_emp')) # 新增接口
admin.view
# 视图层
from datetime import datetime
from flask.views import MethodView
from flask import render_template, redirect, url_for, request
from personal.models import db, Employee, Department
class EmployeelListView(MethodView):
""" 展示员工信息 """
def get(self):
employees = db.session.query(Employee).limit(10) # 取10条
return render_template('admin/emp-list.html', employees=employees)
class EmployeelDeleteView(MethodView):
""" 删除员工 """
def get(self, id=None):
if id:
emp = db.session.query(Employee).get(id) # get,只能根据主键查
if emp:
db.session.delete(emp)
db.session.commit()
return redirect(url_for('admin.emp_list'))
class EmployeeCreateView(MethodView):
""" 创建员工 """
def get(self):
""" get请求的时候为展示信息 """
departments = db.session.query(Department).all()
return render_template('admin/emp-detail.html', departments=departments)
def post(self):
""" post请求时为新增信息 """
emp = Employee(
name=request.form.get('name'),
gender=request.form.get('gender', '男'),
job=request.form.get('job'),
birthdate=datetime.strptime(request.form.get('birthdate'), '%Y-%m-%d'),
idcard=request.form.get('id_card'),
address=request.form.get('address'),
salary=float(request.form.get('salary'))
)
emp.department_id = int(request.form.get('department_id'))
db.session.add(emp)
db.session.commit()
return redirect(url_for('.emp_list'))
personal.__init__
from flask import Blueprint
# 声明蓝图
employee = Blueprint('employee', __name__)
from personal.views import *
# 把视图注册到蓝图里面
employee.add_url_rule('/list/', view_func=EmployeeListView.as_view('emp_list'))
personal.models
from datetime import datetime
from main import db
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}'
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, gender, job, birthdate, idcard, address, salary, 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}'
if __name__ == '__main__':
db.create_all()
personal.view
from flask import render_template
from flask.views import MethodView
from main import db
from .models import Employee
class EmployeeListView(MethodView):
""" 返回前10条数据 """
def get(self):
employees = db.session.query(Employee).all()[:10]
return render_template('admin/emp-list.html', employees=employees)
base.html
信息明细
{% extends 'admin/base.html' %}
{% block stylesheet %}
{% endblock %}
{% block page_head %}
<div class="page-head">
<h3 class="m-b-less">人事列表</h3>
<div class="state-information">
<ol class="breadcrumb m-b-less bg-less">
<li><a href="#">首页</a></li>
<li><a href="#">人事管理</a></li>
<li class="active">人事列表</li>
</ol>
</div>
</div>
{% endblock %}
{% block main_content %}
<div class="wrapper">
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
新增员工
</header>
<div class="panel-body">
<form class="form-horizontal" method="post" action="#" role="form">
<div class="form-group">
<label for="name" class="col-lg-2 col-sm-2 control-label">姓名</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="name" name="name">
</div>
</div>
<div class="form-group">
<label for="department_id" class="col-lg-2 col-sm-2 control-label">部门</label>
<div class="col-lg-3">
<select class="form-control m-b-10" id="department_id" name="department_id">
{% for department in departments %}
<option value="{{ department.id }}">{{ department.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="gender" class="col-lg-2 col-sm-2 control-label">性别</label>
<div class="col-lg-10">
<label>
<input type="radio" name="gender" id="male" value="男" checked>男</label>
<input type="radio" name="gender" id="female" value="女">女</label>
</div>
</div>
<div class="form-group">
<label for="job" class="col-lg-2 col-sm-2 control-label">职位</label>
<div class="col-lg-4">
<input type="text" class="form-control" id="job" name="job">
</div>
</div>
<div class="form-group">
<label for="birthdate" class="col-lg-2 col-sm-2 control-label">生日</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="birthdate" name="birthdate"
placeholder="">
</div>
</div>
<div class="form-group">
<label for="id_card" class="col-lg-2 col-sm-2 control-label">身份证号</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="id_card" name="id_card">
</div>
</div>
<div class="form-group">
<label for="address" class="col-lg-2 col-sm-2 control-label">地址</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="address" name="address" placeholder="">
</div>
</div>
<div class="form-group">
<label for="salary" class="col-lg-2 col-sm-2 control-label">工资</label>
<div class="col-lg-2">
<input type="text" class="form-control" id="salary" name="salary" placeholder="">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary">提交</button>
<input type="reset" class="btn btn-default" value="重置">
<a href=" {{ url_for('admin.emp_list') }} " class="btn btn-default">返回列表</a>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
</div>
{% endblock %}
{% block script %}
{% endblock %}
员工展示列表
{% extends 'admin/base.html' %}
{% block stylesheet %}
{% endblock %}
{% block page_head %}
<div class="page-head">
<h3 class="m-b-less">人事列表</h3>
<div class="state-information">
<ol class="breadcrumb m-b-less bg-less">
<li><a href="#">首页</a></li>
<li><a href="#">人事管理</a></li>
<li class="active">人事列表</li>
</ol>
</div>
</div>
{% endblock %}
{% block main_content %}
<div class="wrapper">
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading head-border">
员工列表
</header>
<table class="table table-striped custom-table table-hover">
<thead>
<tr>
<th>编号</th>
<th class="hidden-xs">姓名</th>
<th>性别</th>
<th>生日</th>
<th>地址</th>
<th class="hidden-xs">操作</th>
</tr>
</thead>
<tbody>
{% for emp in employees %}
<tr>
<td><a href="#">{{ emp.id }}</a></td>
<td>{{ emp.name }}</td>
<td>{{ emp.gender }}</td>
<td>{{ emp.birthdate }}</td>
<td>{{ emp.address }}</td>
<td class="hidden-xs">
<button class="btn btn-success btn-xs"><i class="fa fa-check"></i></button>
<button class="btn btn-primary btn-xs"><i class="fa fa-pencil"></i></button>
<a href="{{ url_for('.emp_del', id=emp.id) }}" class="btn btn-danger btn-xs"><i
class="fa fa-trash-o "></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
</div>
</div>
</div>
{% endblock %}
{% block script %}
{% endblock %}
主入口
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__, static_url_path='') # 初始化app,
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./db/test.db' # 声明数据库类型和地址
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 跟踪改变
app.config['SQLALCHEMY_ECHO'] = True # 打印对应的sql,此操作用sql是怎么样的
db = SQLAlchemy(app) # 创建数据库核心对象并把数据库和app关联起来
# 由于视图需要导入db,所以需要在db产生后再导入蓝图
from personal import employee as blueprint_employee
from admin import admin as blueprint_admin
app.register_blueprint(blueprint_employee, url_prefix='/emp')
app.register_blueprint(blueprint_admin, url_prefix='/admin')
@app.route('/')
def index():
return render_template('admin/emp-list.html')
if __name__ == '__main__':
app.run(debug=True)
数据库情况
列表页
新增页
新增成功,自动跳转到列表页
数据库也存在此数据
删除
手动插入一些数据
讨论群:249728408