__init__.py 25 KB

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