main.py
$!globalPort
$!callback.setFileName("${tableInfo.name}Main.py")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/$tableInfo.obj.name"))
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end
# -*- coding: utf-8 -*-
import logging
import threading
import webbrowser
from DBUtil import DBUtil
from LogUtil import getLogger
from flask import Flask, render_template
from flask import request
from flask_cors import CORS
# html同级
app = Flask(__name__, template_folder=".")
# flask日志输出级别
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
# 项目日志
logger = getLogger("log")
CORS(app, resources='/*')
# 数据库
db = DBUtil("$tableInfo.obj.getParent().getPresentableText()")
# 表名
tableName = "$tableInfo.obj.name"
app.jinja_env.variable_start_string = '{['
app.jinja_env.variable_end_string = ']}'
def request_parse():
if request.method == 'POST' or request.method == 'PUT':
return request.json
elif request.method == 'GET' or request.method == 'DELETE':
return request.args
@app.route('/getList', methods=['GET'])
def getList():
# region 参数
data = request_parse()
pageNum = data.get("pageNum")
pageSize = data.get("pageSize")
parmOrder = data.get("parmOrder")
parmColumn = data.get("parmColumn")
#foreach($column in $tableInfo.fullColumn)
${column.obj.name} = data.get("${column.obj.name}")
#end
# endregion
# region 计算分页
if not pageNum:
pageNum = 1
else:
pageNum = int(pageNum)
if not pageSize:
pageSize = 10
else:
pageSize = int(pageSize)
if pageNum < 0:
pageNum = 0
# 起始位置
selectIndex = (pageNum - 1) * pageSize
if selectIndex < 0:
selectIndex = 0
# endregion
sql = "select * from {} where 1=1 ".format(tableName)
countWhereSql = " where 1=1 "
#foreach($column in $tableInfo.fullColumn)
if ${column.obj.name}:
sql += " and ${column.obj.name} like '%{}%' ".format(${column.obj.name})
countWhereSql += " and ${column.obj.name} like '%{}%'".format(${column.obj.name})
#end
if parmOrder:
orderSql = " order by {} {} ".format(parmColumn, parmOrder)
sql += "{} limit {},{}".format(orderSql, selectIndex, pageSize)
countWhereSql += orderSql
else:
sql += "limit {},{}".format(selectIndex, pageSize)
logger.info("getList()----sql: {}".format(sql))
logger.info("getList()----countWhereSql: {}".format(countWhereSql))
result_data = db.select(sql)
for i in range(len(result_data)):
#foreach($column in $tableInfo.fullColumn)
#if($column.type.equals("java.util.Date"))
result_data[i]["$column.obj.name"] = str(result_data[i]["$column.obj.name"])
#end
#end
pass
count = db.selectCount(tableName, countWhereSql)
return {
"resultCode":200,
"rows": result_data,
"total": count
}
@app.route('/getOne', methods=['GET'])
def getOne():
data = request_parse()
$pk.obj.name = data.get("$pk.obj.name")
sql = "select * from {} where $pk.obj.name = '{}'".format(tableName,$pk.obj.name)
logger.info("getOne()----sql: {}".format(sql))
oneData = db.select(sql)
if oneData:
#foreach($column in $tableInfo.fullColumn)
#if($column.type.equals("java.util.Date"))
oneData[0]["$column.obj.name"] = str(oneData[0]["$column.obj.name"])
#end
#end
return {"resultCode": 200, "data": oneData[0]}
else:
return {"resultCode": 404, "msg": "没有找到此记录"}
@app.route('/update', methods=['PUT'])
def update():
data = request_parse()
#foreach($column in $tableInfo.fullColumn)
${column.obj.name} = data.get("${column.obj.name}")
#end
sql = "update {} set ".format(tableName)
#foreach($column in $tableInfo.otherColumn)
if ${column.obj.name}:
sql += " ${column.obj.name} = '{}' ,".format(${column.obj.name})
#end
sql = sql.strip(",")
sql += " where $pk.obj.name = '{}'".format($pk.obj.name)
logger.info("update()----sql: {}".format(sql))
db.execute(sql)
return {"resultCode": 200}
@app.route('/delete', methods=['DELETE'])
def delete():
data = request_parse()
${pk.obj.name}s = data.getlist("${pk.obj.name}s[]")
for ${pk.obj.name} in ${pk.obj.name}s:
sql = "delete from {} where $pk.obj.name = '{}'".format(tableName,$pk.obj.name)
logger.info("delete()----sql: {}".format(sql))
db.execute(sql)
return {"resultCode": 200}
@app.route('/add', methods=['POST'])
def add():
data = request_parse()
# 移除主键
if '$pk.obj.name' in data.keys():
del data['$pk.obj.name']
logger.info("add()----数据: {}".format(data))
db.insertOne(data,tableName)
return {"resultCode": 200}
@app.route("/")
def index():
return render_template('index.html')
def openUrl(port):
webbrowser.open("http://127.0.0.1:{}".format(port), new=0)
@app.errorhandler(Exception)
def error_handler(e):
logger.error("全局异常捕获: {}".format(e))
data = {
"resultCode": 500,
"msg": str(e)
}
return data
if __name__ == '__main__':
port = $port
if not os.environ.get('WERKZEUG_RUN_MAIN'):
th = threading.Thread(target=openUrl, args=(port,))
th.start()
else:
print("热加载")
app.run(port=port, debug=True)
index.html
$!globalPort
$!callback.setFileName("index.html")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/$tableInfo.obj.name"))
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
#if(!$tableInfo.comment)
<title>$tableInfo.obj.name</title>
#else
<title>$tableInfo.comment</title>
#end
<link rel="stylesheet" href="static/css/element.css">
<script src="static/js/vue-2.6.12.js"></script>
<script src="static/js/element.js"></script>
<script src="static/js/axios.min.js"></script>
<link rel="shortcut icon" href="static/favicon.ico" type="image/x-icon"/>
</head>
<style>
/*body {
width: 80%;
margin: auto;
margin-top: 20px;
}*/
</style>
<body>
<div id="app">
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
#foreach($column in $tableInfo.fullColumn)
#if(!$column.comment)
<el-form-item label="$column.obj.name" prop="$column.obj.name">
#else
<el-form-item label="$column.comment" prop="$column.obj.name">
#end
<el-input
v-model.trim="queryParams.${column.obj.name}"
#if(!$column.comment)
placeholder="请输入$column.obj.name"
#else
placeholder="请输入$column.comment"
#end
clearable
size="small"
@keyup.enter.native="handleQuery"/>
</el-form-item>
#end
<el-form-item>
<el-pagination
background
:current-page.sync="queryParams.pageNum"
:page-sizes="[10, 20, 30, 50, 400]"
:page-size.sync="queryParams.pageSize"
layout="total, sizes, prev, pager, next"
@size-change="getList"
@current-change="getList"
:total="total">
</el-pagination>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10">
<el-col :span="1.5">
<el-button
type="primary"
icon="el-icon-plus"
size="mini"
@click="handleAdd"
>新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
>修改
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
>删除
</el-button>
</el-col>
</el-row>
<el-table v-loading="loading" :data="${tableInfo.obj.name}List" @sort-change="handleSortChange" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center"></el-table-column>
#foreach($column in $tableInfo.fullColumn)
#if(!$column.comment)
<el-table-column label="${column.obj.name}" align="center" sortable prop="${column.obj.name}"></el-table-column>
#else
<el-table-column label="${column.comment}" align="center" sortable prop="${column.obj.name}"></el-table-column>
#end
#end
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
>修改
</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
>删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 添加或修改对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
#foreach($column in $tableInfo.otherColumn)
#if(!$column.comment)
<el-form-item label="${column.obj.name}" prop="${column.obj.name}">
#if($column.type.equals("java.util.Date"))
<el-date-picker clearable size="small" style="width: 200px"
v-model="form.${column.obj.name}"
type="date"
value-format="yyyy-MM-dd"
placeholder="选择${column.obj.name}">
</el-date-picker>
#else
<el-input v-model="form.${column.obj.name}" placeholder="请输入${column.obj.name}"/>
#end
</el-form-item>
#else
<el-form-item label="${column.comment}" prop="${column.obj.name}">
#if($column.type.equals("java.util.Date"))
<el-date-picker clearable size="small" style="width: 200px"
v-model="form.${column.obj.name}"
type="date"
value-format="yyyy-MM-dd"
placeholder="选择${column.comment}">
</el-date-picker>
#else
<el-input v-model="form.${column.obj.name}" placeholder="请输入${column.comment}"/>
#end
</el-form-item>
#end
#end
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
</div>
</div>
</body>
<script>
baseUrl = "http://127.0.0.1:$port"
new Vue({
el: '#app',
data() {
return {
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 总条数
total: 0,
// $tableInfo.obj.name表格数据
${tableInfo.obj.name}List: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 10,
#foreach($column in $tableInfo.fullColumn)
${column.obj.name}:undefined,
#end
parmOrder: undefined,
parmColumn: undefined
},
// 表单参数
form: {},
// 表单校验
rules: {
#foreach ($column in $tableInfo.otherColumn)
#if(!$column.comment)
${column.obj.name}: [ { required: true, message: "$column.obj.name不能为空", trigger: "blur" } ],
#else
${column.obj.name}: [ { required: true, message: "$column.comment不能为空", trigger: "blur" } ],
#end
#end
}
};
},
created() {
this.getList();
},
methods: {
// 查询列表
getList() {
this.loading = true;
axios({
method: 'get',
url: baseUrl + '/getList',
params:this.queryParams,
}).then(res => {
const response = res.data;
const resultCode = response.resultCode
if (resultCode === 200) {
this.${tableInfo.obj.name}List = response.rows;
this.total = response.total;
this.loading = false;
} else {
this.$message({
message: '查询失败,' + response.msg,
type: 'error'
});
}
}).catch(function (error) {
console.log(error);
});
},
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
// 表单重置
reset() {
this.form = {
#foreach ($column in $tableInfo.otherColumn)
$column.obj.name: undefined,
#end
};
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
/** 重置按钮操作 */
resetQuery() {
this.$refs.queryForm.resetFields();
this.handleQuery();
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.${pk.obj.name})
this.single = selection.length!=1
this.multiple = !selection.length
},
// 排序
handleSortChange(column) {
let parmOrder = column.order === "ascending" ? "asc" : "desc"
this.queryParams.parmColumn = column.prop
this.queryParams.parmOrder = parmOrder
if (column.order == null) {
this.queryParams.parmColumn = undefined
this.queryParams.parmOrder = undefined
}
this.getList()
},
/** 新增按钮操作 */
handleAdd() {
this.reset();
this.open = true;
this.title = "添加";
},
/** 修改按钮操作 */
handleUpdate(row) {
this.reset();
const ${pk.obj.name} = row.${pk.obj.name} || this.ids[0]
axios({
method: 'get',
url: baseUrl + '/getOne',
params:{"${pk.obj.name}":${pk.obj.name}},
}).then(res => {
if (res.data.resultCode === 200) {
this.form = res.data.data;
this.open = true;
this.title = "修改";
}else{
this.getList();
this.$message({
message: "查询失败:" + res.data.msg,
type: 'error'
});
}
}).catch(function (error) {
console.log(error);
});
},
/** 提交按钮 */
submitForm: function() {
this.#[[$]]#refs["form"].validate(valid => {
if (valid) {
if (this.form.${pk.obj.name} != undefined) {
axios({
method: 'put',
url: baseUrl + '/update',
data:this.form,
}).then(res => {
if (res.data.resultCode === 200) {
this.$message({
message: '修改成功',
type: 'success'
});
this.open = false;
this.getList();
}else{
this.getList();
this.$message({
message: "修改失败:" + res.data.msg,
type: 'error'
});
}
}).catch(function (error) {
console.log(error);
});
} else {
axios({
method: 'post',
url: baseUrl + '/add',
data:this.form,
}).then(res => {
if (res.data.resultCode === 200) {
this.$message({
message: '新增成功',
type: 'success'
});
this.open = false;
this.getList();
}else{
this.getList();
this.$message({
message: "新增失败:" + res.data.msg,
type: 'error'
});
}
}).catch(function (error) {
console.log(error);
});
}
}
});
},
/** 删除按钮操作 */
handleDelete(row) {
const ${pk.obj.name}s = row.${pk.obj.name} ? [row.${pk.obj.name}] : this.ids
this.$confirm('是否确认删除编号为"' + ${pk.obj.name}s + '"的数据项?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
axios({
method: 'delete',
url: baseUrl + '/delete',
params:{"${pk.obj.name}s":${pk.obj.name}s},
}).then(res => {
if (res.data.resultCode === 200) {
this.$message({
message: '删除成功',
type: 'success'
});
this.open = false;
this.getList();
}else{
this.getList();
this.$message({
message: "删除失败:" + res.data.msg,
type: 'error'
});
}
});
}).catch(() => {
});
},
}
})
</script>
</html>
Global Config
globalPort
#set($port = 666)