__init__.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from re import S
  4. from fastapi import APIRouter, Request, Depends, Form, Body, File, UploadFile, BackgroundTasks
  5. from fastapi.responses import Response
  6. from fastapi.responses import JSONResponse
  7. from database import get_db
  8. from sqlalchemy.orm import Session
  9. from utils import *
  10. from models import *
  11. from urllib import parse
  12. from common.DBgetdata import dbgetdata
  13. from pprint import pprint
  14. from datetime import datetime
  15. # import pandas as pd
  16. from pydantic import BaseModel
  17. import sqlalchemy
  18. import pymysql
  19. import json,time,io
  20. import time, os
  21. import math
  22. import uuid
  23. import re
  24. router = APIRouter()
  25. def contains_special_characters(input_string, special_characters=";|&|$|#|'|\\t|@| "):
  26. """
  27. 判断字符串是否包含特殊符号。
  28. :param input_string: 需要检查的字符串
  29. :param special_characters: 特殊符号的字符串,多个符号用竖线 '|' 分隔
  30. :return: 如果包含特殊符号返回 True,否则返回 False
  31. """
  32. # 创建正则表达式模式
  33. pattern = re.compile('[' + re.escape(special_characters) + ']')
  34. # 搜索字符串中的特殊符号
  35. if pattern.search(input_string):
  36. return True
  37. return False
  38. @router.get('/v1/demo')
  39. @router.post('/v1/demo')
  40. async def test1(request: Request):
  41. data = await request.body()
  42. body = data.decode(encoding='utf-8')
  43. # print(body)
  44. if len(body) > 0:
  45. body = json.loads(body)
  46. print(body)
  47. print([body,{'msg':'good'}])
  48. return body
  49. else:
  50. return body
  51. @router.post('/create_api_service')
  52. async def create_api_service(
  53. request: Request,
  54. db: Session = Depends(get_db)
  55. ):
  56. # print(1)
  57. data = await request.body()
  58. body = data.decode(encoding='utf-8')
  59. if len(body) > 0:
  60. # print(body)
  61. body = json.loads(body)
  62. serviceid = str(uuid.uuid4()).replace("-","")
  63. serviname = body['servicename']
  64. datasource = str(uuid.uuid1())
  65. sqlname = body['sqlname']
  66. id = str(uuid.uuid4())
  67. dbtype = body['dbtype']
  68. if body['dbtype'] == 'pymysql':
  69. host = body['host']
  70. user = body['user']
  71. password = body['password']
  72. database = body['database']
  73. port = body['port']
  74. charset = body['charset']
  75. create_datasource = DatasourceEntity(id= datasource,name=sqlname,scope=serviceid,dbtype=dbtype,host=host,user=user,password=password,database=database,port=port,charset=charset)
  76. # db.add()
  77. # print()
  78. db.add(create_datasource)
  79. sqltext = body['sqltext']
  80. create_command = CommandEntity(id=id,sqltext=sqltext,datasource=datasource,scope=serviceid)
  81. create_api = ApiServiceEntity(id=serviceid,name=serviname)
  82. db.add(create_api)
  83. db.add(create_command)
  84. db.commit()
  85. return serviceid
  86. @router.get('/v1/{service_code:path}')
  87. @router.post('/v1/{service_code:path}')
  88. async def v1(request: Request, background_tasks: BackgroundTasks, db: Session = Depends(get_db)):
  89. service_code = request.path_params.get('service_code')
  90. query_list = parse.parse_qsl(str(request.query_params))
  91. print(query_list)
  92. data = await request.body()
  93. body = data.decode(encoding='utf-8')
  94. if len(body) > 0:
  95. print('[body]', body)
  96. body = json.loads(body)
  97. # print("1111",body)
  98. service_info = db.query(ApiServiceEntity).filter(ApiServiceEntity.id == service_code).first()
  99. if service_info is None:
  100. return {
  101. 'errcode': 1,
  102. 'errmsg': '服务不存在'
  103. }
  104. # print(service_info)
  105. print('service_name', service_info.name)
  106. # print('database_name', database_info.name, database_info.dsn)
  107. command_info = db.query(CommandEntity).filter(CommandEntity.scope == service_code).first()
  108. if command_info is None:
  109. return {
  110. 'errcode': 1,
  111. 'errmsg': '查询命令没配置'
  112. }
  113. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == command_info.datasource).first()
  114. if database_info is None:
  115. return {
  116. 'errcode': 1,
  117. 'errmsg': '数据库没配置'
  118. }
  119. sql = command_info.sqltext
  120. print('sql ==== << ', sql)
  121. meta_data = {}
  122. # 从query获取参数
  123. for (key, val) in query_list:
  124. if key != 'access_token' and key !='page' and key != 'limit' and key !='create_time' and key != 'record_name'and key != 'record_cid':
  125. sql = sql.replace("{" + key + "}", val.replace('全部',''))
  126. elif key =='create_time':
  127. if val != '全部':
  128. sql = sql.replace("{" + key + "}", ('DATE_FORMAT(create_time,\'%Y-%m-%d\') =\''+val+'\' and')) #DATE_FORMAT(create_time,'%Y-%m-%d') ='{create_time}'
  129. else:
  130. sql = sql.replace("{" + key + "}", '')
  131. elif key =='record_name' or key =='record_cid' :
  132. if val != '全部':
  133. sql = sql.replace("{" + key + "}", (key+'=\''+val+'\' and'))
  134. else:
  135. sql = sql.replace("{" + key + "}", '')
  136. # elif key =='record_cid':
  137. # if val != '全部':
  138. # sql = sql.replace("{" + key + "}", ('record_name =\''+val+'\' and'))
  139. # else:
  140. # print(111)
  141. # sql = sql.replace("{" + key + "}", '')
  142. elif key =='page' :
  143. meta_data['page'] = int(val)
  144. elif key == 'limit':
  145. meta_data['limit'] = int(val)
  146. # 从json body获取参数
  147. if len(body) > 0:
  148. print(body)
  149. for (key, val) in body.items():
  150. if key == 'page1' and 'limit1' in body:
  151. if val==-1:
  152. pass
  153. if val == '':
  154. val = '0'
  155. page1 = int(val)
  156. limit1=int(body['limit1'])
  157. print(str((page1-1)*limit1))
  158. sql = sql.replace('{page1}',str((page1-1)*limit1))
  159. # elif key == 'limit1' and 'page1' in body:
  160. # page1 = int(body['page1'])
  161. # limit1 = int(val)
  162. # sql.replace('{page1}', str((page1-1)*limit1))
  163. elif key !='page' and key != 'limit' and key !='create_time':
  164. if isinstance(val, int):
  165. val = str(val)
  166. sql = sql.replace("{" + key + "}", val)
  167. elif key =='create_time':
  168. if val != '全部':
  169. sql = sql.replace("{" + key + "}", ('DATE_FORMAT(create_time,\'%Y-%m-%d\') =\''+val+'\' and')) #DATE_FORMAT(create_time,'%Y-%m-%d') ='{create_time}'
  170. else:
  171. sql = sql.replace("{" + key + "}", '')
  172. elif key =='page' :
  173. if isinstance(val, str):
  174. meta_data['page'] = int(val)
  175. elif isinstance(val, int):
  176. meta_data['page'] = val
  177. elif key == 'limit':
  178. if isinstance(val, str):
  179. meta_data['limit'] = int(val)
  180. elif isinstance(val, int):
  181. meta_data['limit'] = val
  182. elif key == 'taskNo' and val=='':
  183. print("他们又输入空的taskNo啦!")
  184. return [{"text":"兄弟,taskNo不能为空"}]
  185. print('sql ==== >> ', sql)
  186. data = []
  187. if database_info.dbtype == 'psycopg2':
  188. '''
  189. print(1111)
  190. conn = psycopg2.connect(database_info.dsn)
  191. cur = conn.cursor()
  192. cur.execute(sql)
  193. rows = cur.fetchall()
  194. # 字段名列表
  195. colnames = [desc[0] for desc in cur.description]
  196. item = {}
  197. for row in rows:
  198. for col in range(len(colnames)):
  199. field_name = colnames[col]
  200. item[field_name] = row[col]
  201. data.append(item)
  202. conn.close()
  203. '''
  204. elif database_info.dbtype == 'pymysql':
  205. # print(database_info)
  206. conn = pymysql.connect(host=database_info.host,
  207. user=database_info.user,
  208. password=database_info.password,
  209. database=database_info.database,
  210. port=database_info.port,
  211. charset=database_info.charset)
  212. cur = conn.cursor()
  213. cur.execute(sql)
  214. rows = cur.fetchall()
  215. # 字段名列表
  216. colnames = [desc[0] for desc in cur.description]
  217. # print(colnames)
  218. # print(rows)
  219. pages = 1 #总页数
  220. current = 1 #第几页
  221. total = len(rows)
  222. size = len(rows)
  223. # print(size)
  224. if 'page' in meta_data and 'limit' in meta_data:
  225. current = meta_data['page']
  226. size = meta_data['limit']
  227. if (current == 0 or size == 0) and total != 0:
  228. current = 1
  229. size = 5
  230. pages = total//size
  231. if total%size !=0:
  232. pages+=1
  233. start_index = (current-1)*size
  234. end_index = current*size
  235. if pages <= current :
  236. # current = pages
  237. if total == size :
  238. end_index = (current-1)*size+total
  239. elif total%size == 0:
  240. end_index = current*size
  241. else:
  242. end_index = (current-1)*size+total%size
  243. start_index = (current-1)*size
  244. if total ==0:
  245. start_index = end_index =0
  246. # print(start_index,end_index)
  247. for row in range(start_index,end_index):
  248. item = {}
  249. for col in range(len(colnames)):
  250. field_name = colnames[col]
  251. item[field_name] = rows[row][col]
  252. data.append(item)
  253. # print(item)
  254. # for row in rows:
  255. # item = {}
  256. # for col in range(len(colnames)):
  257. # field_name = colnames[col]
  258. # item[field_name] = row[col]
  259. # data.append(item)
  260. # print(item)
  261. # print(data)
  262. conn.close()
  263. return {
  264. 'code': 0,
  265. 'errcode': 0,
  266. 'errmsg': '查询成功',
  267. 'data': {"list":data,
  268. 'pages':pages, # 总页数
  269. 'currentPage':current, #当前页数
  270. # 'current':current,
  271. # 'total' : total,
  272. 'total' : total, # 总数据量
  273. # 'size':size,
  274. 'pageSize':size #页码
  275. }
  276. }
  277. # import time
  278. # print(time)
  279. # if 'ispages' in body:
  280. # try:
  281. # if body['ispages']=='1':
  282. # return {
  283. # 'page': [{"total": pages,
  284. # "page": current}],
  285. # "data":data
  286. # }
  287. # # data['pages'] =
  288. # except:
  289. # pass
  290. #
  291. # #background_tasks.add_task(post_service_method, service_code, body, db)
  292. #
  293. # return data
  294. class CreateApiServiceFrom(BaseModel):
  295. datasource:str
  296. name:str
  297. sqltext:str
  298. serviceid:str=None
  299. @router.post('/v2/create_api_service')
  300. async def create_api_service_v2(
  301. form_data: CreateApiServiceFrom,
  302. request: Request,
  303. db: Session = Depends(get_db)
  304. ):
  305. # print(1)
  306. data = await request.body()
  307. body = data.decode(encoding='utf-8')
  308. if len(body) > 0:
  309. # print(body)
  310. body = json.loads(body)
  311. for param in ['datasource','name','sqltext']:
  312. if param not in body or body[param]=='':
  313. return f'{param}为必填参数,不能不存在'
  314. # 数据库信息校验
  315. datasource = form_data.datasource
  316. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == datasource).first()
  317. if database_info is None:
  318. return JSONResponse(status_code=410, content={
  319. 'errcode': 410,
  320. 'errmsg': f'数据库-{datasource}-不存在'
  321. })
  322. # 接口信息生成及获取
  323. if form_data.serviceid is None:
  324. serviceid = str(uuid.uuid4()).replace("-","")
  325. else:
  326. serviceid = form_data.serviceid
  327. serviname = form_data.name
  328. id = str(uuid.uuid4())
  329. sqltext = form_data.sqltext
  330. # 接口执行校验
  331. if database_info.dbtype == 'pymysql':
  332. try:
  333. conn = pymysql.connect(host=database_info.host,
  334. user=database_info.user,
  335. password=database_info.password,
  336. database=database_info.database,
  337. port=database_info.port,
  338. charset=database_info.charset)
  339. cur = conn.cursor()
  340. # 测试返回
  341. sql = sqltext+' limit 0;'
  342. print(sql)
  343. cur.execute(sql)
  344. colnames = [desc[0] for desc in cur.description]
  345. cur.close()
  346. conn.close()
  347. except Exception as e:
  348. # 捕获其他所有类型的异常
  349. return f"未知错误: {e}"
  350. else:
  351. return '暂不支持除pymysql以外的驱动'
  352. create_command = CommandEntity(id=id,sqltext=sqltext,datasource=datasource,scope=serviceid)
  353. create_api = ApiServiceEntity(id=serviceid,name=serviname,status=1)
  354. db.add(create_api)
  355. db.add(create_command)
  356. db.commit()
  357. return [serviceid,colnames]
  358. @router.post('/v2/update_api_service')
  359. async def update_api_service_v2(
  360. request: Request,
  361. db: Session = Depends(get_db)
  362. ):
  363. # print(1)
  364. data = await request.body()
  365. body = data.decode(encoding='utf-8')
  366. if len(body) > 0:
  367. # print(body)
  368. body = json.loads(body)
  369. for param in ['id','datasource','scope','name','sqltext','status']:
  370. if param not in body or body[param]=='':
  371. return f'{param}为必填参数,不能不存在'
  372. # 数据库信息校验
  373. datasource = body['datasource']
  374. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == datasource).first()
  375. if database_info is None:
  376. return JSONResponse(status_code=410, content={
  377. 'errcode': 410,
  378. 'errmsg': f'数据库-{datasource}-不存在'
  379. })
  380. serviceid = body['scope']
  381. # 判断请求接口是否存在
  382. service_info = db.query(ApiServiceEntity).filter(ApiServiceEntity.id == serviceid).first()
  383. if service_info is None:
  384. return JSONResponse(status_code=410, content={
  385. 'code': 410,
  386. 'msg': f'servicecode{serviceid}服务不存在'
  387. })
  388. command_info = db.query(CommandEntity).filter(CommandEntity.scope == serviceid).first()
  389. if command_info is None:
  390. return JSONResponse(status_code=410, content={
  391. 'code': 410,
  392. 'msg': f'servicecode{serviceid}服务不存在'
  393. })
  394. # 接口信息生成及获取
  395. id = body['id']
  396. serviname = body['name']
  397. sqltext = body['sqltext']
  398. status = body['status']
  399. # 接口执行校验
  400. if database_info.dbtype == 'pymysql':
  401. try:
  402. conn = pymysql.connect(host=database_info.host,
  403. user=database_info.user,
  404. password=database_info.password,
  405. database=database_info.database,
  406. port=database_info.port,
  407. charset=database_info.charset)
  408. cur = conn.cursor()
  409. # 测试返回
  410. sql = sqltext+' limit 0;'
  411. print(sql)
  412. cur.execute(sql)
  413. colnames = [desc[0] for desc in cur.description]
  414. cur.close()
  415. conn.close()
  416. except Exception as e:
  417. # 捕获其他所有类型的异常
  418. return f"未知错误: {e}"
  419. else:
  420. return '暂不支持除pymysql以外的驱动'
  421. # create_command = CommandEntity(id=id,sqltext=sqltext,datasource=datasource,scope=serviceid)
  422. # create_api = ApiServiceEntity(id=serviceid,name=serviname,status=1)
  423. # db.add(create_api)
  424. # db.add(create_command)
  425. service_info.id=serviceid
  426. service_info.name=serviname
  427. service_info.status=status
  428. command_info.id=id
  429. command_info.sqltext=sqltext
  430. command_info.datasource=datasource
  431. command_info.scope=serviceid
  432. db.commit()
  433. return [serviceid,colnames]
  434. @router.post('/v2/create_datasource')
  435. async def create_create_datasource_v2(
  436. request: Request,
  437. db: Session = Depends(get_db)
  438. ):
  439. # print(1)
  440. data = await request.body()
  441. body = data.decode(encoding='utf-8')
  442. if len(body) > 0:
  443. # print(body)
  444. body = json.loads(body)
  445. # 检查入参
  446. for param in ['datasourcename','dbtype','host','user','password','database','port','charset']:
  447. if param not in body or body[param]=='':
  448. return f'{param}为必填参数,不能不存在'
  449. datasource = str(uuid.uuid1())
  450. datasourcename = body['datasourcename']
  451. dbtype = body['dbtype']
  452. if body['dbtype'] == 'pymysql':
  453. host = body['host']
  454. user = body['user']
  455. password = body['password']
  456. database = body['database']
  457. port = body['port']
  458. charset = body['charset']
  459. # 数据库连通性校验
  460. try:
  461. conn = pymysql.connect(host=host,
  462. user=user,
  463. password=password,
  464. database=database,
  465. port=port,
  466. charset=charset)
  467. cur = conn.cursor()
  468. # 测试返回
  469. sql = ' select now()'
  470. print(sql)
  471. cur.execute(sql)
  472. testresult = cur.fetchall()
  473. cur.close()
  474. conn.close()
  475. except Exception as e:
  476. # 捕获其他所有类型的异常
  477. return f"未知错误: {e}"
  478. create_datasource = DatasourceEntity(id=datasource, name=datasourcename, scope='', dbtype=dbtype, host=host,
  479. user=user, password=password, database=database, port=port,
  480. charset=charset)
  481. db.add(create_datasource)
  482. else:
  483. return f'暂不支持{dbtype}'
  484. db.commit()
  485. return [datasource,testresult]
  486. @router.post('/v2/update_datasource')
  487. async def create_update_datasource_v2(
  488. request: Request,
  489. db: Session = Depends(get_db)
  490. ):
  491. # print(1)
  492. data = await request.body()
  493. body = data.decode(encoding='utf-8')
  494. if len(body) > 0:
  495. # print(body)
  496. body = json.loads(body)
  497. # 检查入参
  498. for param in ['id','datasourcename','dbtype','host','user','password','database','port','charset']:
  499. if param not in body or body[param]=='':
  500. return f'{param}为必填参数,不能不存在'
  501. # 根据数据库id检测是否存在
  502. datasource = body['id']
  503. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == datasource).first()
  504. if database_info is None:
  505. return JSONResponse(status_code=410, content={
  506. 'errcode': 410,
  507. 'errmsg': f'数据库{datasource}不存在'
  508. })
  509. datasourcename = body['datasourcename']
  510. dbtype = body['dbtype']
  511. if body['dbtype'] == 'pymysql':
  512. host = body['host']
  513. user = body['user']
  514. password = body['password']
  515. database = body['database']
  516. port = body['port']
  517. charset = body['charset']
  518. # 数据库连通性校验
  519. try:
  520. conn = pymysql.connect(host=host,
  521. user=user,
  522. password=password,
  523. database=database,
  524. port=port,
  525. charset=charset)
  526. cur = conn.cursor()
  527. # 测试返回
  528. sql = ' select now()'
  529. print(sql)
  530. cur.execute(sql)
  531. testresult = cur.fetchall()
  532. cur.close()
  533. conn.close()
  534. except Exception as e:
  535. # 捕获其他所有类型的异常
  536. return f"未知错误: {e}"
  537. # create_datasource = DatasourceEntity(id=datasource, name=datasourcename, scope='', dbtype=dbtype, host=host,
  538. # user=user, password=password, database=database, port=port,
  539. # charset=charset)
  540. # db.add(create_datasource)
  541. database_info.name = datasourcename
  542. database_info.dbtype = dbtype
  543. database_info.host = host
  544. database_info.user = user
  545. database_info.password = password
  546. database_info.database = database
  547. database_info.port = port
  548. database_info.charset = charset
  549. else:
  550. return f'暂不支持{dbtype}'
  551. db.commit()
  552. return [datasource,testresult]
  553. @router.get('/v2/{serviceid}')
  554. @router.post('/v2/{serviceid}')
  555. # @router.post('/v2/{servicecode}')
  556. async def v2(serviceid:str,request: Request, db: Session = Depends(get_db)):
  557. # 获取请求头 servicecode
  558. # if service_code is None:
  559. # service_code = request.headers.get('servicecode')
  560. # print(serviceid)
  561. if serviceid is None:
  562. return JSONResponse(status_code=410, content= {
  563. 'code': 410,
  564. 'msg': "请求头servicecode未传参"
  565. })
  566. # 判断请求接口是否存在
  567. service_info = db.query(ApiServiceEntity).filter(ApiServiceEntity.id == serviceid).first()
  568. if service_info is None:
  569. return JSONResponse(status_code=410, content={
  570. 'code': 410,
  571. 'msg': 'servicecode服务不存在'
  572. })
  573. # print(service_code)
  574. # 判断请求接口对应数据库是否存在
  575. command_info = db.query(CommandEntity).filter(CommandEntity.scope == serviceid).first()
  576. if command_info is None:
  577. return JSONResponse(status_code=410, content={
  578. 'code': 410,
  579. 'msg': '查询命令没配置'
  580. })
  581. # 判断请求接口对应数据库是否存在
  582. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == command_info.datasource).first()
  583. if database_info is None:
  584. return JSONResponse(status_code=410, content={
  585. 'errcode': 410,
  586. 'errmsg': '数据库没配置'
  587. })
  588. # 获取接口对应的sql
  589. sql = command_info.sqltext
  590. print('sql ==== << ', sql)
  591. # 从params和body获取参数
  592. # query_list = parse.parse_qsl(str(request.query_params))
  593. # print(query_list)
  594. data = await request.body()
  595. body = data.decode(encoding='utf-8')
  596. if len(body) > 0:
  597. body = json.loads(body)
  598. # 分页器 页数和页码的设置
  599. size = 10
  600. current = 1
  601. if "size" in body:
  602. if isinstance(body['size'], str):
  603. size = int(body['size'])
  604. elif isinstance(body['size'], int):
  605. size = body['size']
  606. if size >100:
  607. size = 100
  608. if "current" in body:
  609. if isinstance(body['current'], str):
  610. current = int(body['current'])
  611. elif isinstance(body['current'], int):
  612. current = body['current']
  613. if current<=0:
  614. current=1
  615. # 接口sql的参数替换
  616. if 'query' in body:
  617. for (key, val) in body['query'].items():
  618. if isinstance(val, int):
  619. val = str(val)
  620. if contains_special_characters(val):
  621. return JSONResponse(status_code=411, content={
  622. 'code': 411,
  623. 'msg': f'参数{key}含特殊符号:;、&、$、#、\'、\\t、@、空格等'
  624. })
  625. sql = sql.replace("{" + key + "}", val)
  626. print('sql ==== >> ', sql)
  627. data = []
  628. # 数据库类型为mysql情况下
  629. if database_info.dbtype == 'pymysql':
  630. # 数据库连接
  631. conn = pymysql.connect(host=database_info.host,
  632. user=database_info.user,
  633. password=database_info.password,
  634. database=database_info.database,
  635. port=database_info.port,
  636. charset=database_info.charset)
  637. cur = conn.cursor()
  638. # 查总数据量,分页数据处理
  639. totalsql = f'select count(*) from ({sql})t'
  640. print(totalsql)
  641. cur.execute(totalsql)
  642. total = cur.fetchone()[0]
  643. pages,pagesmod = divmod(total, size)
  644. print(total,pages,pagesmod)
  645. if pagesmod!=0:
  646. pages+=1
  647. print(pages,pagesmod)
  648. if total <size :
  649. size = total
  650. # 正式查询
  651. sql = sql+f' limit {size*(current-1)}, {size};'
  652. print(sql,size)
  653. cur.execute(sql)
  654. rows = cur.fetchall()
  655. colnames = [desc[0] for desc in cur.description]
  656. for row in range(size):
  657. item = {}
  658. for col in range(len(colnames)):
  659. field_name = colnames[col]
  660. item[field_name] = rows[row][col]
  661. data.append(item)
  662. # 数据库关闭
  663. cur.close()
  664. conn.close()
  665. else:
  666. return JSONResponse(status_code=410, content={
  667. 'code': 410,
  668. 'msg': '接口对应数据库暂不支持'
  669. })
  670. return {
  671. 'code': 0,
  672. 'msg': 'success',
  673. 'data': {"list": data,
  674. 'pages': pages, # 总页数
  675. 'currentPage': current, # 当前页数
  676. # 'current':current,
  677. # 'total' : total,
  678. 'total': total, # 总数据量
  679. # 'size':size,
  680. 'pageSize': size # 页码
  681. }
  682. }
  683. else:
  684. return JSONResponse(status_code=410, content={
  685. 'code': 410,
  686. 'msg': 'body不能为空'
  687. })