__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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=";|&|$|#|'|@| "):
  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. if isinstance(val, float):
  167. val = str(val)
  168. sql = sql.replace("{" + key + "}", val)
  169. elif key =='create_time':
  170. if val != '全部':
  171. sql = sql.replace("{" + key + "}", ('DATE_FORMAT(create_time,\'%Y-%m-%d\') =\''+val+'\' and')) #DATE_FORMAT(create_time,'%Y-%m-%d') ='{create_time}'
  172. else:
  173. sql = sql.replace("{" + key + "}", '')
  174. elif key =='page' :
  175. if isinstance(val, str):
  176. meta_data['page'] = int(val)
  177. elif isinstance(val, int):
  178. meta_data['page'] = val
  179. elif key == 'limit':
  180. if isinstance(val, str):
  181. meta_data['limit'] = int(val)
  182. elif isinstance(val, int):
  183. meta_data['limit'] = val
  184. elif key == 'taskNo' and val=='':
  185. print("他们又输入空的taskNo啦!")
  186. return [{"text":"兄弟,taskNo不能为空"}]
  187. print('sql ==== >> ', sql)
  188. data = []
  189. if database_info.dbtype == 'psycopg2':
  190. '''
  191. print(1111)
  192. conn = psycopg2.connect(database_info.dsn)
  193. cur = conn.cursor()
  194. cur.execute(sql)
  195. rows = cur.fetchall()
  196. # 字段名列表
  197. colnames = [desc[0] for desc in cur.description]
  198. item = {}
  199. for row in rows:
  200. for col in range(len(colnames)):
  201. field_name = colnames[col]
  202. item[field_name] = row[col]
  203. data.append(item)
  204. conn.close()
  205. '''
  206. elif database_info.dbtype == 'pymysql':
  207. # print(database_info)
  208. conn = pymysql.connect(host=database_info.host,
  209. user=database_info.user,
  210. password=database_info.password,
  211. database=database_info.database,
  212. port=database_info.port,
  213. charset=database_info.charset)
  214. cur = conn.cursor()
  215. cur.execute(sql)
  216. rows = cur.fetchall()
  217. # 字段名列表
  218. colnames = [desc[0] for desc in cur.description]
  219. # print(colnames)
  220. # print(rows)
  221. pages = 1 #总页数
  222. current = 1 #第几页
  223. total = len(rows)
  224. size = len(rows)
  225. # print(size)
  226. if 'page' in meta_data and 'limit' in meta_data:
  227. current = meta_data['page']
  228. size = meta_data['limit']
  229. if (current == 0 or size == 0) and total != 0:
  230. current = 1
  231. size = 5
  232. pages = total//size
  233. if total%size !=0:
  234. pages+=1
  235. start_index = (current-1)*size
  236. end_index = current*size
  237. if pages <= current :
  238. # current = pages
  239. if total == size :
  240. end_index = (current-1)*size+total
  241. elif total%size == 0:
  242. end_index = current*size
  243. else:
  244. end_index = (current-1)*size+total%size
  245. start_index = (current-1)*size
  246. if total ==0:
  247. start_index = end_index =0
  248. # print(start_index,end_index)
  249. for row in range(start_index,end_index):
  250. item = {}
  251. for col in range(len(colnames)):
  252. field_name = colnames[col]
  253. item[field_name] = rows[row][col]
  254. data.append(item)
  255. # print(item)
  256. # for row in rows:
  257. # item = {}
  258. # for col in range(len(colnames)):
  259. # field_name = colnames[col]
  260. # item[field_name] = row[col]
  261. # data.append(item)
  262. # print(item)
  263. # print(data)
  264. conn.close()
  265. return {
  266. 'code': 0,
  267. 'errcode': 0,
  268. 'errmsg': '查询成功',
  269. 'data': {"list":data,
  270. 'pages':pages, # 总页数
  271. 'currentPage':current, #当前页数
  272. # 'current':current,
  273. # 'total' : total,
  274. 'total' : total, # 总数据量
  275. # 'size':size,
  276. 'pageSize':size #页码
  277. }
  278. }
  279. # import time
  280. # print(time)
  281. # if 'ispages' in body:
  282. # try:
  283. # if body['ispages']=='1':
  284. # return {
  285. # 'page': [{"total": pages,
  286. # "page": current}],
  287. # "data":data
  288. # }
  289. # # data['pages'] =
  290. # except:
  291. # pass
  292. #
  293. # #background_tasks.add_task(post_service_method, service_code, body, db)
  294. #
  295. # return data
  296. class CreateApiServiceFrom(BaseModel):
  297. datasource:str
  298. name:str
  299. sqltext:str
  300. serviceid:str=None
  301. @router.post('/v2/create_api_service')
  302. async def create_api_service_v2(
  303. form_data: CreateApiServiceFrom,
  304. request: Request,
  305. db: Session = Depends(get_db)
  306. ):
  307. # print(1)
  308. data = await request.body()
  309. body = data.decode(encoding='utf-8')
  310. if len(body) > 0:
  311. # print(body)
  312. body = json.loads(body)
  313. for param in ['datasource','name','sqltext']:
  314. if param not in body or body[param]=='':
  315. return f'{param}为必填参数,不能不存在'
  316. # 数据库信息校验
  317. datasource = form_data.datasource
  318. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == datasource).first()
  319. if database_info is None:
  320. return JSONResponse(status_code=410, content={
  321. 'errcode': 410,
  322. 'errmsg': f'数据库-{datasource}-不存在'
  323. })
  324. # 接口信息生成及获取
  325. if form_data.serviceid is None:
  326. serviceid = str(uuid.uuid4()).replace("-","")
  327. else:
  328. serviceid = form_data.serviceid
  329. serviname = form_data.name
  330. id = str(uuid.uuid4())
  331. sqltext = form_data.sqltext
  332. # 接口执行校验
  333. if database_info.dbtype == 'pymysql':
  334. try:
  335. conn = pymysql.connect(host=database_info.host,
  336. user=database_info.user,
  337. password=database_info.password,
  338. database=database_info.database,
  339. port=database_info.port,
  340. charset=database_info.charset)
  341. cur = conn.cursor()
  342. # 测试返回
  343. sql = sqltext+' limit 0;'
  344. print(sql)
  345. cur.execute(sql)
  346. colnames = [desc[0] for desc in cur.description]
  347. cur.close()
  348. conn.close()
  349. except Exception as e:
  350. # 捕获其他所有类型的异常
  351. return f"未知错误: {e}"
  352. else:
  353. return '暂不支持除pymysql以外的驱动'
  354. create_command = CommandEntity(id=id,sqltext=sqltext,datasource=datasource,scope=serviceid)
  355. create_api = ApiServiceEntity(id=serviceid,name=serviname,status=1)
  356. db.add(create_api)
  357. db.add(create_command)
  358. db.commit()
  359. return [serviceid,colnames]
  360. @router.post('/v2/update_api_service')
  361. async def update_api_service_v2(
  362. request: Request,
  363. db: Session = Depends(get_db)
  364. ):
  365. # print(1)
  366. data = await request.body()
  367. body = data.decode(encoding='utf-8')
  368. if len(body) > 0:
  369. # print(body)
  370. body = json.loads(body)
  371. for param in ['id','datasource','scope','name','sqltext','status']:
  372. if param not in body or body[param]=='':
  373. return f'{param}为必填参数,不能不存在'
  374. # 数据库信息校验
  375. datasource = body['datasource']
  376. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == datasource).first()
  377. if database_info is None:
  378. return JSONResponse(status_code=410, content={
  379. 'errcode': 410,
  380. 'errmsg': f'数据库-{datasource}-不存在'
  381. })
  382. serviceid = body['scope']
  383. # 判断请求接口是否存在
  384. service_info = db.query(ApiServiceEntity).filter(ApiServiceEntity.id == serviceid).first()
  385. if service_info is None:
  386. return JSONResponse(status_code=410, content={
  387. 'code': 410,
  388. 'msg': f'servicecode{serviceid}服务不存在'
  389. })
  390. command_info = db.query(CommandEntity).filter(CommandEntity.scope == serviceid).first()
  391. if command_info is None:
  392. return JSONResponse(status_code=410, content={
  393. 'code': 410,
  394. 'msg': f'servicecode{serviceid}服务不存在'
  395. })
  396. # 接口信息生成及获取
  397. id = body['id']
  398. serviname = body['name']
  399. sqltext = body['sqltext']
  400. status = body['status']
  401. # 接口执行校验
  402. if database_info.dbtype == 'pymysql':
  403. try:
  404. conn = pymysql.connect(host=database_info.host,
  405. user=database_info.user,
  406. password=database_info.password,
  407. database=database_info.database,
  408. port=database_info.port,
  409. charset=database_info.charset)
  410. cur = conn.cursor()
  411. # 测试返回
  412. sql = sqltext+' limit 0;'
  413. print(sql)
  414. cur.execute(sql)
  415. colnames = [desc[0] for desc in cur.description]
  416. cur.close()
  417. conn.close()
  418. except Exception as e:
  419. # 捕获其他所有类型的异常
  420. return f"未知错误: {e}"
  421. else:
  422. return '暂不支持除pymysql以外的驱动'
  423. # create_command = CommandEntity(id=id,sqltext=sqltext,datasource=datasource,scope=serviceid)
  424. # create_api = ApiServiceEntity(id=serviceid,name=serviname,status=1)
  425. # db.add(create_api)
  426. # db.add(create_command)
  427. service_info.id=serviceid
  428. service_info.name=serviname
  429. service_info.status=status
  430. command_info.id=id
  431. command_info.sqltext=sqltext
  432. command_info.datasource=datasource
  433. command_info.scope=serviceid
  434. db.commit()
  435. return [serviceid,colnames]
  436. @router.post('/v2/create_datasource')
  437. async def create_create_datasource_v2(
  438. request: Request,
  439. db: Session = Depends(get_db)
  440. ):
  441. # print(1)
  442. data = await request.body()
  443. body = data.decode(encoding='utf-8')
  444. if len(body) > 0:
  445. # print(body)
  446. body = json.loads(body)
  447. # 检查入参
  448. for param in ['datasourcename','dbtype','host','user','password','database','port','charset']:
  449. if param not in body or body[param]=='':
  450. return f'{param}为必填参数,不能不存在'
  451. datasource = str(uuid.uuid1())
  452. datasourcename = body['datasourcename']
  453. dbtype = body['dbtype']
  454. if body['dbtype'] == 'pymysql':
  455. host = body['host']
  456. user = body['user']
  457. password = body['password']
  458. database = body['database']
  459. port = body['port']
  460. charset = body['charset']
  461. # 数据库连通性校验
  462. try:
  463. conn = pymysql.connect(host=host,
  464. user=user,
  465. password=password,
  466. database=database,
  467. port=port,
  468. charset=charset)
  469. cur = conn.cursor()
  470. # 测试返回
  471. sql = ' select now()'
  472. print(sql)
  473. cur.execute(sql)
  474. testresult = cur.fetchall()
  475. cur.close()
  476. conn.close()
  477. except Exception as e:
  478. # 捕获其他所有类型的异常
  479. return f"未知错误: {e}"
  480. create_datasource = DatasourceEntity(id=datasource, name=datasourcename, scope='', dbtype=dbtype, host=host,
  481. user=user, password=password, database=database, port=port,
  482. charset=charset)
  483. db.add(create_datasource)
  484. else:
  485. return f'暂不支持{dbtype}'
  486. db.commit()
  487. return [datasource,testresult]
  488. @router.post('/v2/update_datasource')
  489. async def create_update_datasource_v2(
  490. request: Request,
  491. db: Session = Depends(get_db)
  492. ):
  493. # print(1)
  494. data = await request.body()
  495. body = data.decode(encoding='utf-8')
  496. if len(body) > 0:
  497. # print(body)
  498. body = json.loads(body)
  499. # 检查入参
  500. for param in ['id','datasourcename','dbtype','host','user','password','database','port','charset']:
  501. if param not in body or body[param]=='':
  502. return f'{param}为必填参数,不能不存在'
  503. # 根据数据库id检测是否存在
  504. datasource = body['id']
  505. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == datasource).first()
  506. if database_info is None:
  507. return JSONResponse(status_code=410, content={
  508. 'errcode': 410,
  509. 'errmsg': f'数据库{datasource}不存在'
  510. })
  511. datasourcename = body['datasourcename']
  512. dbtype = body['dbtype']
  513. if body['dbtype'] == 'pymysql':
  514. host = body['host']
  515. user = body['user']
  516. password = body['password']
  517. database = body['database']
  518. port = body['port']
  519. charset = body['charset']
  520. # 数据库连通性校验
  521. try:
  522. conn = pymysql.connect(host=host,
  523. user=user,
  524. password=password,
  525. database=database,
  526. port=port,
  527. charset=charset)
  528. cur = conn.cursor()
  529. # 测试返回
  530. sql = ' select now()'
  531. print(sql)
  532. cur.execute(sql)
  533. testresult = cur.fetchall()
  534. cur.close()
  535. conn.close()
  536. except Exception as e:
  537. # 捕获其他所有类型的异常
  538. return f"未知错误: {e}"
  539. # create_datasource = DatasourceEntity(id=datasource, name=datasourcename, scope='', dbtype=dbtype, host=host,
  540. # user=user, password=password, database=database, port=port,
  541. # charset=charset)
  542. # db.add(create_datasource)
  543. database_info.name = datasourcename
  544. database_info.dbtype = dbtype
  545. database_info.host = host
  546. database_info.user = user
  547. database_info.password = password
  548. database_info.database = database
  549. database_info.port = port
  550. database_info.charset = charset
  551. else:
  552. return f'暂不支持{dbtype}'
  553. db.commit()
  554. return [datasource,testresult]
  555. @router.get('/v2/{serviceid}')
  556. @router.post('/v2/{serviceid}')
  557. # @router.post('/v2/{servicecode}')
  558. async def v2(serviceid:str,request: Request, db: Session = Depends(get_db)):
  559. # 获取请求头 servicecode
  560. # if service_code is None:
  561. # service_code = request.headers.get('servicecode')
  562. # print(serviceid)
  563. if serviceid is None:
  564. return JSONResponse(status_code=410, content= {
  565. 'code': 410,
  566. 'msg': "请求头servicecode未传参"
  567. })
  568. # 判断请求接口是否存在
  569. service_info = db.query(ApiServiceEntity).filter(ApiServiceEntity.id == serviceid).first()
  570. if service_info is None:
  571. return JSONResponse(status_code=410, content={
  572. 'code': 410,
  573. 'msg': 'servicecode服务不存在'
  574. })
  575. # print(service_code)
  576. # 判断请求接口对应数据库是否存在
  577. command_info = db.query(CommandEntity).filter(CommandEntity.scope == serviceid).first()
  578. if command_info is None:
  579. return JSONResponse(status_code=410, content={
  580. 'code': 410,
  581. 'msg': '查询命令没配置'
  582. })
  583. # 判断请求接口对应数据库是否存在
  584. database_info = db.query(DatasourceEntity).filter(DatasourceEntity.id == command_info.datasource).first()
  585. if database_info is None:
  586. return JSONResponse(status_code=410, content={
  587. 'errcode': 410,
  588. 'errmsg': '数据库没配置'
  589. })
  590. # 获取接口对应的sql
  591. sql = command_info.sqltext
  592. print('sql ==== << ', sql)
  593. # 从params和body获取参数
  594. # query_list = parse.parse_qsl(str(request.query_params))
  595. # print(query_list)
  596. data = await request.body()
  597. body = data.decode(encoding='utf-8')
  598. size = 10
  599. current = 1
  600. if len(body) > 0:
  601. body = json.loads(body)
  602. # 分页器 页数和页码的设置
  603. if "size" in body:
  604. if isinstance(body['size'], str):
  605. size = int(body['size'])
  606. elif isinstance(body['size'], int):
  607. size = body['size']
  608. if size >100:
  609. size = 100
  610. if "current" in body:
  611. if isinstance(body['current'], str):
  612. current = int(body['current'])
  613. elif isinstance(body['current'], int):
  614. current = body['current']
  615. if current<=0:
  616. current=1
  617. # 接口sql的参数替换
  618. if 'query' in body:
  619. for (key, val) in body['query'].items():
  620. if isinstance(val, int):
  621. val = str(val)
  622. if isinstance(val, float):
  623. val = str(val)
  624. if contains_special_characters(val):
  625. return JSONResponse(status_code=411, content={
  626. 'code': 411,
  627. 'msg': f'参数{key}含特殊符号:;、&、$、#、\'、\\t、@、空格等'
  628. })
  629. sql = sql.replace("{" + key + "}", val)
  630. print('sql ==== >> ', sql)
  631. data = []
  632. # 数据库类型为mysql情况下
  633. if database_info.dbtype == 'pymysql':
  634. # 数据库连接
  635. conn = pymysql.connect(host=database_info.host,
  636. user=database_info.user,
  637. password=database_info.password,
  638. database=database_info.database,
  639. port=database_info.port,
  640. charset=database_info.charset)
  641. cur = conn.cursor()
  642. # 查总数据量,分页数据处理
  643. totalsql = f'select count(*) from ({sql})t'
  644. print(totalsql)
  645. cur.execute(totalsql)
  646. total = cur.fetchone()[0]
  647. pages,pagesmod = divmod(total, size)
  648. print(total,pages,pagesmod)
  649. if pagesmod!=0:
  650. pages+=1
  651. print(pages,pagesmod)
  652. if total <size :
  653. size = total
  654. # 正式查询
  655. sql = sql+f' limit {size*(current-1)}, {size};'
  656. print(sql,size)
  657. cur.execute(sql)
  658. rows = cur.fetchall()
  659. colnames = [desc[0] for desc in cur.description]
  660. for row in range(len(rows)):
  661. item = {}
  662. for col in range(len(colnames)):
  663. field_name = colnames[col]
  664. item[field_name] = rows[row][col]
  665. data.append(item)
  666. # 数据库关闭
  667. cur.close()
  668. conn.close()
  669. else:
  670. return JSONResponse(status_code=410, content={
  671. 'code': 410,
  672. 'msg': '接口对应数据库暂不支持'
  673. })
  674. return {
  675. 'code': 0,
  676. 'msg': 'success',
  677. 'rows': data,
  678. 'pages': pages, # 总页数
  679. 'currentPage': current, # 当前页数
  680. # 'current':current,
  681. # 'total' : total,
  682. 'total': total, # 总数据量
  683. # 'size':size,
  684. 'pageSize': size # 页码
  685. }
  686. # else:
  687. # return JSONResponse(status_code=410, content={
  688. # 'code': 410,
  689. # 'msg': 'body不能为空'
  690. # })