测开之路一百四十五: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)
数据库情况
列表页
新增页
新增成功,自动跳转到列表页
数据库也存在此数据
删除
手动插入一些数据
测开之路一百四十五:SQLAlchemy与后台模板整合之新增、查询、删除的更多相关文章
- 测开之路一百四十九:jinja2模板之宏
jinja2是python的模板引擎, 在写python web使用的过程中,macro可以节省大量的代码 比如上一篇的渲染页面 <!DOCTYPE html><html lang= ...
- 测开之路一百四十八:WTForms表单验证
使用WTForms表单验证,可以在数据建模时就设置验证信息和错误提示 创建模型时,设置验证内容,如必填.格式.长度 from flask_wtf import Formfrom wtforms imp ...
- 测开之路一百四十六:WTForms之表单应用
WTForms主要是两个功能:1.生成HTML标签 2.对数据格式进行验证 官网:https://wtforms.readthedocs.io/en/stable/ 这篇介绍用wtform生成htm ...
- 测开之路一百四十四:ORM之SQLAlchemy查询
在上一篇的基础上,插入数据 查询 Department.query.all() # 用表对象查db.session.query(Department).all() # 用db对象查 查询前两条,直接p ...
- 测开之路一百四十二:ORM框架之SQLAlchemy建库、建表、数据库操作
flask-SQLAlchemy是在原生SQLAlchemy的基础之上做了一层封装,安装flask-SQLAlchemy会自动安装SQLAlchemy 安装 传统的sql建表建字段 通过flask-S ...
- 测开之路一百二十五:flask之urlencode参数传递和解析
当get请求传参时,用?分隔参数和域名,用&分隔参数,如果参数里面本身就有&符号就会识别不出来,还是会当成分隔符,所以这些数据在传输的时候,就需要转义,现在普遍是转成urlencode ...
- 测开之路一百四十七:用WTForms实现编辑功能
接上一篇的内容 把原先的数据库模型全部给默认值,后面form赋值的时候就不用传位置参数了 把视图逻辑修改一下 # 视图层from datetime import datetimefrom flask. ...
- 测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建
基于前一篇内容,可以使用模型的结构 目录结构 main,入口层 from flask import Flaskfrom flask_sqlalchemy import SQLAlchemy app = ...
- 测开之路一百三十九:会话管理之cookie写入、读取、和更新
机制:服务器端发送的小段文本信息存储在客户端硬盘 功能:记录用户偏好,请求.页面.站点间共享信息 特点:易丢失.安全隐患 添加cookie,需要用到make_respons.set_cookie @a ...
随机推荐
- pycharm 激激活码
pycharm 激活码 [20191224亲测可用] http://lookdiv.com/neet/youd/codes.html
- java.lang.ClassNotFoundException: org.apache.jsp.login_jsp
<span style="font-family: Simsun; background-color: rgb(255, 255, 255);">想必大家在用Eclip ...
- killall - 以名字方式来杀死进程
SYNOPSIS (总览) killall [-egiqvw] [-signal] name ... killall -l killall -V DESCRIPTION (描述) killall 发送 ...
- tomcat同个端口配置多个项目后无后缀的页面跳转
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- [DllImport("kernel32.dll")]使用
C#中读取ini配置文件 [DllImport("kernel32.dll")] using System;using System.Collections.Generic;usi ...
- P1058 立体图题解
小渊是个聪明的孩子,他经常会给周围的小朋友们将写自己认为有趣的内容.最近,他准备给小朋友们讲解立体图,请你帮他画出立体图. 小渊有一块面积为m \times nm×n的矩形区域,上面有m \times ...
- AI换脸教程:DeepFaceLab使用教程(1.安装及分解视频)
首先需要选择合适的DeepFaceLab下载(https://www.deepfacelabs.com/list-5-1.html),然后安装相应的显卡驱动,如果已经准备好这些工作,那么恭喜你,终于开 ...
- TypeError: Cannot read property 'splice' of undefined
splice是删除数组里的项,报这个错证明你点前面那个并不是个数组,仔细一看,还真是数组名称写错了
- Java注解Annotation与自定义注解详解
Java注解简介 开发中经常使用到注解,在项目中也偶尔会见到过自定义注解,今天就来探讨一下这个注解是什么鬼,以及注解的应用场景和如何自定义注解. 下面列举开发中常见的注解 @Override:用于标识 ...
- elementUI中的el-xxx标签解释
点击跳转地址:https://blog.csdn.net/Tom__cy/article/details/89680067 el-col :整体,el-container: 主体区域el-toolti ...