测开之路一百四十五: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 ...
随机推荐
- 新霸哥带你轻松玩转Oracle数据库
接触过软件开发的朋友可能都会知道oracle,在开发的过程中,数据存储都可能会用到oracle的,因为oracle具有处理速度快,安全级别特别的高.但是有一个缺点就是比较的贵,只有一个大型的公司才有可 ...
- java.lang.String (JDK 1.8)
研究一个类之前我们来说说类的构成: 一个类主要分为几个部分:分别是类的定义(类的继承,接口的实现),全局变量方法,属性,内部类等. 第一点: 实现的接口 public fin ...
- 019-zabbix数据库表详解
https://www.cnblogs.com/yaoyaojcy/p/10367945.html 1. 查看目前zabbix系统所有数据表: 1 2 3 4 5 6 7 8 9 10 11 12 1 ...
- python 类的成员及继承
1. @staticmethod 静态方法 静态方法不能访问实例变量和类变量,除了身处类里面,所以只能通过类调用以外,它其实和类没有什么关系.如果想要用它访问实例变量或类变量,需要把实例和类传递给函数 ...
- 整合Spring Data JPA与Spring MVC: 分页和排序pageable
https://www.tianmaying.com/tutorial/spring-jpa-page-sort Spring Data Jpa对于分页以及排序的查询也有着完美的支持,接下来,我们来学 ...
- python中导入from appium import webdriver时报错:ModuleNotFoundError: No module named 'appium'
1.检查一下有没有安装Appium-Python-Client,执行语句:pip install Appium-Python-Client进行安装 2.安装后,出现ModuleNotFoundErro ...
- HDU - 4358 Boring counting (树上启发式合并/线段树合并)
题目链接 题意:统计树上每个结点中恰好出现了k次的颜色数. dsu on tree/线段树合并裸题. 启发式合并1:(748ms) #include<bits/stdc++.h> usin ...
- echarts实现心脏图的滚动三种实现方法
1.改变dataset 2.移动scrollbar 3.修改echarts自带的dataZoom的start和end
- vue打包多页报错webpackJsonp is not defined
找到build→webpack.prod.conf.js→找到HtmlWebpackPlugin插件,添加如下配置即可 chunks: ['manifest', 'vendor', 'app']
- sourceTree 添加 ssh key 方法
1.使用 git 客户的生成公私钥:id_rsa.id_rsa.pub 1.1设置Git的user name和email: $ git config --global user.name " ...