接口测试平台(三)项目管理
创建表模型
在项目根目录apps下创建文件:models.py
from exts import db
from datetime import datetime
class EntityBase(object):
def to_json(self):
fields = self.__dict__
if "_sa_instance_state" in fields:
del fields["_sa_instance_state"]
return fields
class Project(db.Model,EntityBase):
__tablename__ = 'ProjectInfo' # 项目
id=db.Column(db.Integer,primary_key=True,autoincrement=True) # primary_key 为true,主键
project_name = db.Column(db.String(100), nullable=False) # 项目名称
responsible_user = db.Column(db.String(50)) # 项目负责人
test_user = db.Column(db.String(50)) # 测试人员
dev_user = db.Column(db.String(50)) # 开发人员
pro_desc = db.Column(db.String(50)) # 项目描述
create_time =db.Column(db.DateTime, default=datetime.now) # 创建时间
update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now) # 更新时间
修改views.py,添加代码:from apps.models import Project
数据迁移
在项目根目录终端输入命令:python manager.py db init
报错提示没有flask.compat这个模块,打开报错的文件:F:\workspace\test\HttprunnerManager\venv\lib\site-packages\flask_script_init.py
将报错的地方from ._compat import text_type改成from flask_script._compat import text_type,然后保存
重新执行命令:python manager.py db init,环境初始化成功
在项目根目录会生成一个migrations文件夹
执行命令:python manager.py db migrate
报错提示:No module named 'pymysql'
根据提示先安装pymysql:pip install pymysql
然后再执行:python manager.py db migrate
执行成功,这时候数据库会创建一个表:alembic_version
执行命令:python manager.py db upgrade
执行成功后,数据库会创建表:projectinfo
后端接口
项目管理的功能有:添加项目、修改项目、删除项目、项目列表
修改文件models.py:
def __init__(self, project_name, responsible_user, test_user, dev_user, pro_desc):
self.project_name = project_name
self.responsible_user = responsible_user
self.test_user = test_user
self.dev_user = dev_user
self.pro_desc = pro_desc
添加项目
views.py添加代码:
# 添加项目
@bp.route('/add_project/', methods=['post'])
def add_project():
# 获取前端参数
form_data = json.loads(request.form.get('form_data'))
project_name = form_data['project_name']
responsible_user = form_data['responsible_user']
test_user = form_data['test_user']
dev_user = form_data['dev_user']
pro_desc = form_data['pro_desc']
add_obj = Project(project_name=project_name, responsible_user=responsible_user, test_user=test_user, dev_user=dev_user, pro_desc=pro_desc) # 添加数据obj
try:
db.session.add(add_obj)
db.session.commit()
return jsonify({'code': 0, 'msg': '新增项目成功'})
except Exception as e:
return jsonify({'code': 1, 'msg': str(e)})
修改项目
views.py添加代码:
@bp.route('/edit_project/', methods=['post'])
def edit_project():
# 获取前端参数
form_data = json.loads(request.form.get('form_data'))
id = form_data['id']
project_name = form_data['project_name']
responsible_user = form_data['responsible_user']
test_user = form_data['test_user']
dev_user = form_data['dev_user']
pro_desc = form_data['pro_desc']
edit_obj = Project.query.get(id) # 要修改的数据
try:
edit_obj.project_name = project_name
edit_obj.responsible_user = responsible_user
edit_obj.test_user = test_user
edit_obj.dev_user = dev_user
edit_obj.pro_desc = pro_desc
db.session.commit()
return jsonify({'code': 0, 'msg': '编辑项目成功'})
except Exception as e:
return jsonify({'code': 1, 'msg': str(e)})
删除项目
views.py添加代码:
# 删除项目
@bp.route('/del_project/', methods=['POST'])
def del_project():
# 获取前端参数
project_ids = request.values.get('project_id').split(',')
try:
db.session.query(Project).filter(Project.id.in_(project_ids)).delete(synchronize_session=False)
db.session.commit()
return jsonify({'code': 0, 'msg': '删除接口成功'})
except Exception as e:
return jsonify({'code': 1, 'msg': str(e)})
这里是批量删除,所以前端传参是一个数组
项目列表
views.py添加代码:
# 获取项目列表数据
@bp.route("/get_project/", methods=['GET'])
def get_project():
limit = request.args.get('limit')
page = request.args.get('page')
project_name = request.args.get('project_name')
paginates = Project.query.filter(Project.project_name.like("%" + project_name + "%")).order_by(
Project.create_time.desc()).paginate(page=int(page), per_page=int(limit))
projects = paginates.items
count = paginates.total
data = []
for project in projects:
project = dict(id=project.id, project_name=project.project_name, responsible_user=project.responsible_user,
test_user=project.test_user, dev_user=project.dev_user, pro_desc=project.pro_desc,
create_time=project.create_time.strftime('%Y-%m-%d %H:%M:%S'))
print('project:', project)
data.append(project)
# print('data:', data)
res = {'code': 0, 'msg': '获取数据成功', 'count': count, 'data': data}
return jsonify(res)
这里加了个项目名称模糊查询的功能,所以前端传参加一个project_name
前端
前端使用UI框架layui_V2.7.6版本,将layui的资源放到项目根目录下的static文件夹下
修改templates文件夹下的project.html文件:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>接口自动化</title>
<link href="../static/css/layui.css" rel="stylesheet">
<script src="../static/layui.js"></script>
<script>
layui.use(['table','layer'],function () {
var $ = layui.$, table = layui.table, form = layui.form
table.render({
elem:'#table_project',
id:'table_project',
url:'/get_project/',
method:'get',
where:{'project_name':''},
limit:10,
limits:[10,20,50],
cols:[[
{type: 'checkbox', fixed: 'left'},
{field:'id',title:'ID',fixed:true,width:70},
{field:'project_name',title:'项目名称'},
{field:'responsible_user',title:'项目负责人'},
{field:'test_user',title:'测试人员'},
{field:'dev_user',title:'开发人员'},
{field:'pro_desc',title:'描述'},
{field:'create_time',title:'创建时间',width:160}
]],
page: true,
height: 'full-80',
toolbar: '#toolbar',
defaultToolbar: ['filter', 'exports']
})
//监听头部事件
table.on('toolbar(table_project)',function(obj){
// 获取列表勾选数据的Id
var checkStatus = table.checkStatus(obj.config.id);
{#console.log('勾选数据:',checkStatus.data[0])#}
function getCheckIds() { //获取表格选中ID
var idsArray = [];
for (var i = 0; i < checkStatus.data.length; i++) {
idsArray.push(checkStatus.data[i].id);
}
ids = idsArray.toString();
return ids
}
if(obj.event==='search'){
var project_name = $('#project_name_search').val()
//执行重载
table.reloadData('table_project', {
page: {
curr: 1 //重新从第 1 页开始
}
,where: {
project_name: project_name
}
})
}else if(obj.event==='add') {
var index_add_project = layer.open({
type: 1, //iframe
title: '新增项目',
area: ['500px', '389px'],
shade: 0.4,
content: $('#add_project'),
success: function () {
form.on('submit(add_project_sub)', function(data) {
var form_data = {form_data: JSON.stringify(data.field)};
$.ajax({
data: form_data,
type: "post",
dataType: "JSON",
url: '/add_project/',
success:function (result) {
if (result.code===0){
layer.close(index_add_project);
layer.msg(result.msg,{icon: 6});
table.reloadData('table_project');
} else {
layer.alert(result.msg,{icon: 5});
}
}
})
})
}
})
}else if(obj.event==='edit') {
if (checkStatus.data.length === 0) {
layer.alert('请先勾选数据')
} else if (checkStatus.data.length !== 1) {
layer.alert('只能勾选一条数据')
} else {
var index_edit_project = layer.open({
type: 1, //iframe
title: '编辑项目',
area: ['500px', '389px'],
shade: 0.4,
content: $('#edit_project'),
success: function () {
form.val('edit_project', checkStatus.data[0]);
form.on('submit(edit_project_sub)', function(data) {
var form_data = {form_data: JSON.stringify(data.field)};
$.ajax({
data: form_data,
type: "post",
dataType: "JSON",
url: '/edit_project/',
success:function (result) {
if (result.code===0){
layer.close(index_edit_project);
layer.msg(result.msg,{icon: 6});
table.reloadData('table_project');
} else {
layer.alert(result.msg,{icon: 5});
}
}
})
})
}
})
}
}else if(obj.event==='del') {
if (checkStatus.data.length===0) {
layer.alert('请先勾选数据')
} else {
layer.confirm('确认删除?', function (index) {
layer.close(index);
$.ajax({
url: '/del_project/',
data: {project_id: getCheckIds()},
dataType: "json",
type: 'post',
async: false, //同步请求
success: function (result) {
if (result.code === 0) {
console.log('删除成功了')
layer.msg(result.msg, {icon: 6});
table.reloadData('table_project');
}else {
console.log('删除失败')
layer.alert(result.msg,{icon: 5});
}
}
})
})
}
}
})
})
</script>
<style>
.layui-body{padding: 0px 150px;left:0px}
</style>
</head>
<body>
<!--菜单-->
<ul class="layui-nav">
<li class="layui-nav-item layui-this"><a href="/">项目管理</a></li>
<li class="layui-nav-item"><a href="/modules/">模块管理</a></li>
<li class="layui-nav-item"><a href="/api/">接口管理</a></li>
<li class="layui-nav-item"><a href="/testcase/">用例管理</a></li>
<li class="layui-nav-item"><a href="/testtask/">任务管理</a></li>
</ul>
<!--表格-->
<div class="layui-body my-body" style="overflow-x:auto;overflow-y:auto">
<table class="layui-hide" id="table_project" lay-filter="table_project"></table>
<!--头部左侧工具栏-->
<script type="text/html" id="toolbar">
<div class="layui-btn-container" style="font-size: inherit">
<div class="layui-inline" style="width: 150px;margin-bottom: 10px;margin-right: 10px;">
<input class="layui-input" name="project_name_search" id="project_name_search" autocomplete="off" placeholder="请输入项目名称">
</div>
<button class="layui-btn layui-btn-normal" lay-event="search"><i class="layui-icon"></i>搜索</button>
<button class="layui-btn" lay-event="add"><i class="layui-icon"></i>新增项目</button>
<button class="layui-btn layui-btn-warm" lay-event="edit"><i class="layui-icon"></i>编辑</button>
<button class="layui-btn layui-btn-danger" lay-event="del"><i class="layui-icon"></i>删除</button>
</div>
</script>
</div>
<!--添加项目-->
<div id="add_project" style="padding: 10px;display: none">
<form class="layui-form layui-form-pane">
<div id="project_name" class="layui-form-item">
<label class="layui-form-label">项目名称</label>
<div class="layui-input-block">
<input type="text" name="project_name" lay-verify="required" autocomplete="off" placeholder="请输入项目名称" class="layui-input">
</div>
</div>
<div>
<div id="responsible_user" class="layui-form-item">
<label class="layui-form-label">项目负责人</label>
<div class="layui-input-block">
<input type="text" name="responsible_user" autocomplete="off" placeholder="项目负责人" class="layui-input">
</div>
</div>
</div>
<div>
<div id="test_user" class="layui-form-item">
<label class="layui-form-label">测试人员</label>
<div class="layui-input-block">
<input type="text" name="test_user" autocomplete="off" placeholder="测试人员" class="layui-input">
</div>
</div>
</div>
<div>
<div id="dev_user" class="layui-form-item">
<label class="layui-form-label">开发人员</label>
<div class="layui-input-block">
<input type="text" name="dev_user" autocomplete="off" placeholder="请输入开发人员" class="layui-input">
</div>
</div>
</div>
<div>
<div id="pro_desc" class="layui-form-item">
<label class="layui-form-label">描述</label>
<div class="layui-input-block">
<input type="text" name="pro_desc" autocomplete="off" placeholder="请输入项目描述" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block" style="text-align: right;margin-right: 20px;margin-top: 10px;">
<button lay-submit type="button" class="layui-btn" id="commit" lay-filter="add_project_sub" >提交</button>
</div>
</div>
</form>
</div>
<!--修改项目-->
<div id="edit_project" style="padding: 10px;display: none">
<form class="layui-form layui-form-pane" lay-filter="edit_project">
<div id="id" class="layui-form-item" style="display: none">
<label classid="layui-form-label">项目id</label>
<div class="layui-input-block">
<input type="text" name="id" lay-verify="required" autocomplete="off" class="layui-input">
</div>
</div>
<div id="project_name" class="layui-form-item">
<label class="layui-form-label">项目名称</label>
<div class="layui-input-block">
<input type="text" name="project_name" lay-verify="required" autocomplete="off" placeholder="请输入项目名称" class="layui-input">
</div>
</div>
<div>
<div id="responsible_user" class="layui-form-item">
<label class="layui-form-label">项目负责人</label>
<div class="layui-input-block">
<input type="text" name="responsible_user" autocomplete="off" placeholder="项目负责人" class="layui-input">
</div>
</div>
</div>
<div>
<div id="test_user" class="layui-form-item">
<label class="layui-form-label">测试人员</label>
<div class="layui-input-block">
<input type="text" name="test_user" autocomplete="off" placeholder="测试人员" class="layui-input">
</div>
</div>
</div>
<div>
<div id="dev_user" class="layui-form-item">
<label class="layui-form-label">开发人员</label>
<div class="layui-input-block">
<input type="text" name="dev_user" autocomplete="off" placeholder="请输入开发人员" class="layui-input">
</div>
</div>
</div>
<div>
<div id="pro_desc" class="layui-form-item">
<label class="layui-form-label">描述</label>
<div class="layui-input-block">
<input type="text" name="pro_desc" autocomplete="off" placeholder="请输入项目描述" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block" style="text-align: right;margin-right: 20px;margin-top: 10px;">
<button lay-submit type="button" class="layui-btn" id="commit" lay-filter="edit_project_sub" >提交</button>
</div>
</div>
</form>
</div>
</body>
</html>
浏览器访问:http://127.0.0.1:5000/
这时候就可以正常的添加、修改、删除、搜索项目了