main.py

  1. $!globalPort
  2. $!callback.setFileName("${tableInfo.name}Main.py")
  3. $!callback.setSavePath($tool.append($tableInfo.savePath, "/$tableInfo.obj.name"))
  4. #if(!$tableInfo.pkColumn.isEmpty())
  5. #set($pk = $tableInfo.pkColumn.get(0))
  6. #end
  7. # -*- coding: utf-8 -*-
  8. import logging
  9. import threading
  10. import webbrowser
  11. from DBUtil import DBUtil
  12. from LogUtil import getLogger
  13. from flask import Flask, render_template
  14. from flask import request
  15. from flask_cors import CORS
  16. # html同级
  17. app = Flask(__name__, template_folder=".")
  18. # flask日志输出级别
  19. log = logging.getLogger('werkzeug')
  20. log.setLevel(logging.ERROR)
  21. # 项目日志
  22. logger = getLogger("log")
  23. CORS(app, resources='/*')
  24. # 数据库
  25. db = DBUtil("$tableInfo.obj.getParent().getPresentableText()")
  26. # 表名
  27. tableName = "$tableInfo.obj.name"
  28. app.jinja_env.variable_start_string = '{['
  29. app.jinja_env.variable_end_string = ']}'
  30. def request_parse():
  31. if request.method == 'POST' or request.method == 'PUT':
  32. return request.json
  33. elif request.method == 'GET' or request.method == 'DELETE':
  34. return request.args
  35. @app.route('/getList', methods=['GET'])
  36. def getList():
  37. # region 参数
  38. data = request_parse()
  39. pageNum = data.get("pageNum")
  40. pageSize = data.get("pageSize")
  41. parmOrder = data.get("parmOrder")
  42. parmColumn = data.get("parmColumn")
  43. #foreach($column in $tableInfo.fullColumn)
  44. ${column.obj.name} = data.get("${column.obj.name}")
  45. #end
  46. # endregion
  47. # region 计算分页
  48. if not pageNum:
  49. pageNum = 1
  50. else:
  51. pageNum = int(pageNum)
  52. if not pageSize:
  53. pageSize = 10
  54. else:
  55. pageSize = int(pageSize)
  56. if pageNum < 0:
  57. pageNum = 0
  58. # 起始位置
  59. selectIndex = (pageNum - 1) * pageSize
  60. if selectIndex < 0:
  61. selectIndex = 0
  62. # endregion
  63. sql = "select * from {} where 1=1 ".format(tableName)
  64. countWhereSql = " where 1=1 "
  65. #foreach($column in $tableInfo.fullColumn)
  66. if ${column.obj.name}:
  67. sql += " and ${column.obj.name} like '%{}%' ".format(${column.obj.name})
  68. countWhereSql += " and ${column.obj.name} like '%{}%'".format(${column.obj.name})
  69. #end
  70. if parmOrder:
  71. orderSql = " order by {} {} ".format(parmColumn, parmOrder)
  72. sql += "{} limit {},{}".format(orderSql, selectIndex, pageSize)
  73. countWhereSql += orderSql
  74. else:
  75. sql += "limit {},{}".format(selectIndex, pageSize)
  76. logger.info("getList()----sql: {}".format(sql))
  77. logger.info("getList()----countWhereSql: {}".format(countWhereSql))
  78. result_data = db.select(sql)
  79. for i in range(len(result_data)):
  80. #foreach($column in $tableInfo.fullColumn)
  81. #if($column.type.equals("java.util.Date"))
  82. result_data[i]["$column.obj.name"] = str(result_data[i]["$column.obj.name"])
  83. #end
  84. #end
  85. pass
  86. count = db.selectCount(tableName, countWhereSql)
  87. return {
  88. "resultCode":200,
  89. "rows": result_data,
  90. "total": count
  91. }
  92. @app.route('/getOne', methods=['GET'])
  93. def getOne():
  94. data = request_parse()
  95. $pk.obj.name = data.get("$pk.obj.name")
  96. sql = "select * from {} where $pk.obj.name = '{}'".format(tableName,$pk.obj.name)
  97. logger.info("getOne()----sql: {}".format(sql))
  98. oneData = db.select(sql)
  99. if oneData:
  100. #foreach($column in $tableInfo.fullColumn)
  101. #if($column.type.equals("java.util.Date"))
  102. oneData[0]["$column.obj.name"] = str(oneData[0]["$column.obj.name"])
  103. #end
  104. #end
  105. return {"resultCode": 200, "data": oneData[0]}
  106. else:
  107. return {"resultCode": 404, "msg": "没有找到此记录"}
  108. @app.route('/update', methods=['PUT'])
  109. def update():
  110. data = request_parse()
  111. #foreach($column in $tableInfo.fullColumn)
  112. ${column.obj.name} = data.get("${column.obj.name}")
  113. #end
  114. sql = "update {} set ".format(tableName)
  115. #foreach($column in $tableInfo.otherColumn)
  116. if ${column.obj.name}:
  117. sql += " ${column.obj.name} = '{}' ,".format(${column.obj.name})
  118. #end
  119. sql = sql.strip(",")
  120. sql += " where $pk.obj.name = '{}'".format($pk.obj.name)
  121. logger.info("update()----sql: {}".format(sql))
  122. db.execute(sql)
  123. return {"resultCode": 200}
  124. @app.route('/delete', methods=['DELETE'])
  125. def delete():
  126. data = request_parse()
  127. ${pk.obj.name}s = data.getlist("${pk.obj.name}s[]")
  128. for ${pk.obj.name} in ${pk.obj.name}s:
  129. sql = "delete from {} where $pk.obj.name = '{}'".format(tableName,$pk.obj.name)
  130. logger.info("delete()----sql: {}".format(sql))
  131. db.execute(sql)
  132. return {"resultCode": 200}
  133. @app.route('/add', methods=['POST'])
  134. def add():
  135. data = request_parse()
  136. # 移除主键
  137. if '$pk.obj.name' in data.keys():
  138. del data['$pk.obj.name']
  139. logger.info("add()----数据: {}".format(data))
  140. db.insertOne(data,tableName)
  141. return {"resultCode": 200}
  142. @app.route("/")
  143. def index():
  144. return render_template('index.html')
  145. def openUrl(port):
  146. webbrowser.open("http://127.0.0.1:{}".format(port), new=0)
  147. @app.errorhandler(Exception)
  148. def error_handler(e):
  149. logger.error("全局异常捕获: {}".format(e))
  150. data = {
  151. "resultCode": 500,
  152. "msg": str(e)
  153. }
  154. return data
  155. if __name__ == '__main__':
  156. port = $port
  157. if not os.environ.get('WERKZEUG_RUN_MAIN'):
  158. th = threading.Thread(target=openUrl, args=(port,))
  159. th.start()
  160. else:
  161. print("热加载")
  162. app.run(port=port, debug=True)

index.html

  1. $!globalPort
  2. $!callback.setFileName("index.html")
  3. $!callback.setSavePath($tool.append($tableInfo.savePath, "/$tableInfo.obj.name"))
  4. #if(!$tableInfo.pkColumn.isEmpty())
  5. #set($pk = $tableInfo.pkColumn.get(0))
  6. #end
  7. <!DOCTYPE html>
  8. <html lang="zh">
  9. <head>
  10. <meta charset="UTF-8">
  11. #if(!$tableInfo.comment)
  12. <title>$tableInfo.obj.name</title>
  13. #else
  14. <title>$tableInfo.comment</title>
  15. #end
  16. <link rel="stylesheet" href="static/css/element.css">
  17. <script src="static/js/vue-2.6.12.js"></script>
  18. <script src="static/js/element.js"></script>
  19. <script src="static/js/axios.min.js"></script>
  20. <link rel="shortcut icon" href="static/favicon.ico" type="image/x-icon"/>
  21. </head>
  22. <style>
  23. /*body {
  24. width: 80%;
  25. margin: auto;
  26. margin-top: 20px;
  27. }*/
  28. </style>
  29. <body>
  30. <div id="app">
  31. <div class="app-container">
  32. <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
  33. #foreach($column in $tableInfo.fullColumn)
  34. #if(!$column.comment)
  35. <el-form-item label="$column.obj.name" prop="$column.obj.name">
  36. #else
  37. <el-form-item label="$column.comment" prop="$column.obj.name">
  38. #end
  39. <el-input
  40. v-model.trim="queryParams.${column.obj.name}"
  41. #if(!$column.comment)
  42. placeholder="请输入$column.obj.name"
  43. #else
  44. placeholder="请输入$column.comment"
  45. #end
  46. clearable
  47. size="small"
  48. @keyup.enter.native="handleQuery"/>
  49. </el-form-item>
  50. #end
  51. <el-form-item>
  52. <el-pagination
  53. background
  54. :current-page.sync="queryParams.pageNum"
  55. :page-sizes="[10, 20, 30, 50, 400]"
  56. :page-size.sync="queryParams.pageSize"
  57. layout="total, sizes, prev, pager, next"
  58. @size-change="getList"
  59. @current-change="getList"
  60. :total="total">
  61. </el-pagination>
  62. </el-form-item>
  63. <el-form-item>
  64. <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
  65. <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
  66. </el-form-item>
  67. </el-form>
  68. <el-row :gutter="10">
  69. <el-col :span="1.5">
  70. <el-button
  71. type="primary"
  72. icon="el-icon-plus"
  73. size="mini"
  74. @click="handleAdd"
  75. >新增
  76. </el-button>
  77. </el-col>
  78. <el-col :span="1.5">
  79. <el-button
  80. type="success"
  81. icon="el-icon-edit"
  82. size="mini"
  83. :disabled="single"
  84. @click="handleUpdate"
  85. >修改
  86. </el-button>
  87. </el-col>
  88. <el-col :span="1.5">
  89. <el-button
  90. type="danger"
  91. icon="el-icon-delete"
  92. size="mini"
  93. :disabled="multiple"
  94. @click="handleDelete"
  95. >删除
  96. </el-button>
  97. </el-col>
  98. </el-row>
  99. <el-table v-loading="loading" :data="${tableInfo.obj.name}List" @sort-change="handleSortChange" @selection-change="handleSelectionChange">
  100. <el-table-column type="selection" width="55" align="center"></el-table-column>
  101. #foreach($column in $tableInfo.fullColumn)
  102. #if(!$column.comment)
  103. <el-table-column label="${column.obj.name}" align="center" sortable prop="${column.obj.name}"></el-table-column>
  104. #else
  105. <el-table-column label="${column.comment}" align="center" sortable prop="${column.obj.name}"></el-table-column>
  106. #end
  107. #end
  108. <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
  109. <template slot-scope="scope">
  110. <el-button
  111. size="mini"
  112. type="text"
  113. icon="el-icon-edit"
  114. @click="handleUpdate(scope.row)"
  115. >修改
  116. </el-button>
  117. <el-button
  118. size="mini"
  119. type="text"
  120. icon="el-icon-delete"
  121. @click="handleDelete(scope.row)"
  122. >删除
  123. </el-button>
  124. </template>
  125. </el-table-column>
  126. </el-table>
  127. <!-- 添加或修改对话框 -->
  128. <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
  129. <el-form ref="form" :model="form" :rules="rules" label-width="80px">
  130. #foreach($column in $tableInfo.otherColumn)
  131. #if(!$column.comment)
  132. <el-form-item label="${column.obj.name}" prop="${column.obj.name}">
  133. #if($column.type.equals("java.util.Date"))
  134. <el-date-picker clearable size="small" style="width: 200px"
  135. v-model="form.${column.obj.name}"
  136. type="date"
  137. value-format="yyyy-MM-dd"
  138. placeholder="选择${column.obj.name}">
  139. </el-date-picker>
  140. #else
  141. <el-input v-model="form.${column.obj.name}" placeholder="请输入${column.obj.name}"/>
  142. #end
  143. </el-form-item>
  144. #else
  145. <el-form-item label="${column.comment}" prop="${column.obj.name}">
  146. #if($column.type.equals("java.util.Date"))
  147. <el-date-picker clearable size="small" style="width: 200px"
  148. v-model="form.${column.obj.name}"
  149. type="date"
  150. value-format="yyyy-MM-dd"
  151. placeholder="选择${column.comment}">
  152. </el-date-picker>
  153. #else
  154. <el-input v-model="form.${column.obj.name}" placeholder="请输入${column.comment}"/>
  155. #end
  156. </el-form-item>
  157. #end
  158. #end
  159. </el-form>
  160. <div slot="footer" class="dialog-footer">
  161. <el-button type="primary" @click="submitForm">确 定</el-button>
  162. <el-button @click="cancel">取 消</el-button>
  163. </div>
  164. </el-dialog>
  165. </div>
  166. </div>
  167. </body>
  168. <script>
  169. baseUrl = "http://127.0.0.1:$port"
  170. new Vue({
  171. el: '#app',
  172. data() {
  173. return {
  174. // 遮罩层
  175. loading: true,
  176. // 选中数组
  177. ids: [],
  178. // 非单个禁用
  179. single: true,
  180. // 非多个禁用
  181. multiple: true,
  182. // 总条数
  183. total: 0,
  184. // $tableInfo.obj.name表格数据
  185. ${tableInfo.obj.name}List: [],
  186. // 弹出层标题
  187. title: "",
  188. // 是否显示弹出层
  189. open: false,
  190. // 查询参数
  191. queryParams: {
  192. pageNum: 1,
  193. pageSize: 10,
  194. #foreach($column in $tableInfo.fullColumn)
  195. ${column.obj.name}:undefined,
  196. #end
  197. parmOrder: undefined,
  198. parmColumn: undefined
  199. },
  200. // 表单参数
  201. form: {},
  202. // 表单校验
  203. rules: {
  204. #foreach ($column in $tableInfo.otherColumn)
  205. #if(!$column.comment)
  206. ${column.obj.name}: [ { required: true, message: "$column.obj.name不能为空", trigger: "blur" } ],
  207. #else
  208. ${column.obj.name}: [ { required: true, message: "$column.comment不能为空", trigger: "blur" } ],
  209. #end
  210. #end
  211. }
  212. };
  213. },
  214. created() {
  215. this.getList();
  216. },
  217. methods: {
  218. // 查询列表
  219. getList() {
  220. this.loading = true;
  221. axios({
  222. method: 'get',
  223. url: baseUrl + '/getList',
  224. params:this.queryParams,
  225. }).then(res => {
  226. const response = res.data;
  227. const resultCode = response.resultCode
  228. if (resultCode === 200) {
  229. this.${tableInfo.obj.name}List = response.rows;
  230. this.total = response.total;
  231. this.loading = false;
  232. } else {
  233. this.$message({
  234. message: '查询失败,' + response.msg,
  235. type: 'error'
  236. });
  237. }
  238. }).catch(function (error) {
  239. console.log(error);
  240. });
  241. },
  242. // 取消按钮
  243. cancel() {
  244. this.open = false;
  245. this.reset();
  246. },
  247. // 表单重置
  248. reset() {
  249. this.form = {
  250. #foreach ($column in $tableInfo.otherColumn)
  251. $column.obj.name: undefined,
  252. #end
  253. };
  254. },
  255. /** 搜索按钮操作 */
  256. handleQuery() {
  257. this.queryParams.pageNum = 1;
  258. this.getList();
  259. },
  260. /** 重置按钮操作 */
  261. resetQuery() {
  262. this.$refs.queryForm.resetFields();
  263. this.handleQuery();
  264. },
  265. // 多选框选中数据
  266. handleSelectionChange(selection) {
  267. this.ids = selection.map(item => item.${pk.obj.name})
  268. this.single = selection.length!=1
  269. this.multiple = !selection.length
  270. },
  271. // 排序
  272. handleSortChange(column) {
  273. let parmOrder = column.order === "ascending" ? "asc" : "desc"
  274. this.queryParams.parmColumn = column.prop
  275. this.queryParams.parmOrder = parmOrder
  276. if (column.order == null) {
  277. this.queryParams.parmColumn = undefined
  278. this.queryParams.parmOrder = undefined
  279. }
  280. this.getList()
  281. },
  282. /** 新增按钮操作 */
  283. handleAdd() {
  284. this.reset();
  285. this.open = true;
  286. this.title = "添加";
  287. },
  288. /** 修改按钮操作 */
  289. handleUpdate(row) {
  290. this.reset();
  291. const ${pk.obj.name} = row.${pk.obj.name} || this.ids[0]
  292. axios({
  293. method: 'get',
  294. url: baseUrl + '/getOne',
  295. params:{"${pk.obj.name}":${pk.obj.name}},
  296. }).then(res => {
  297. if (res.data.resultCode === 200) {
  298. this.form = res.data.data;
  299. this.open = true;
  300. this.title = "修改";
  301. }else{
  302. this.getList();
  303. this.$message({
  304. message: "查询失败:" + res.data.msg,
  305. type: 'error'
  306. });
  307. }
  308. }).catch(function (error) {
  309. console.log(error);
  310. });
  311. },
  312. /** 提交按钮 */
  313. submitForm: function() {
  314. this.#[[$]]#refs["form"].validate(valid => {
  315. if (valid) {
  316. if (this.form.${pk.obj.name} != undefined) {
  317. axios({
  318. method: 'put',
  319. url: baseUrl + '/update',
  320. data:this.form,
  321. }).then(res => {
  322. if (res.data.resultCode === 200) {
  323. this.$message({
  324. message: '修改成功',
  325. type: 'success'
  326. });
  327. this.open = false;
  328. this.getList();
  329. }else{
  330. this.getList();
  331. this.$message({
  332. message: "修改失败:" + res.data.msg,
  333. type: 'error'
  334. });
  335. }
  336. }).catch(function (error) {
  337. console.log(error);
  338. });
  339. } else {
  340. axios({
  341. method: 'post',
  342. url: baseUrl + '/add',
  343. data:this.form,
  344. }).then(res => {
  345. if (res.data.resultCode === 200) {
  346. this.$message({
  347. message: '新增成功',
  348. type: 'success'
  349. });
  350. this.open = false;
  351. this.getList();
  352. }else{
  353. this.getList();
  354. this.$message({
  355. message: "新增失败:" + res.data.msg,
  356. type: 'error'
  357. });
  358. }
  359. }).catch(function (error) {
  360. console.log(error);
  361. });
  362. }
  363. }
  364. });
  365. },
  366. /** 删除按钮操作 */
  367. handleDelete(row) {
  368. const ${pk.obj.name}s = row.${pk.obj.name} ? [row.${pk.obj.name}] : this.ids
  369. this.$confirm('是否确认删除编号为"' + ${pk.obj.name}s + '"的数据项?', "警告", {
  370. confirmButtonText: "确定",
  371. cancelButtonText: "取消",
  372. type: "warning"
  373. }).then(() => {
  374. axios({
  375. method: 'delete',
  376. url: baseUrl + '/delete',
  377. params:{"${pk.obj.name}s":${pk.obj.name}s},
  378. }).then(res => {
  379. if (res.data.resultCode === 200) {
  380. this.$message({
  381. message: '删除成功',
  382. type: 'success'
  383. });
  384. this.open = false;
  385. this.getList();
  386. }else{
  387. this.getList();
  388. this.$message({
  389. message: "删除失败:" + res.data.msg,
  390. type: 'error'
  391. });
  392. }
  393. });
  394. }).catch(() => {
  395. });
  396. },
  397. }
  398. })
  399. </script>
  400. </html>

Global Config

globalPort

  1. #set($port = 666)