api.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. from natsort.natsort import order_by_index
  2. from sqlalchemy import func
  3. from models import *
  4. import requests
  5. import json
  6. from logger import logger
  7. from serial.tools import list_ports
  8. from model import PhotoRecord
  9. import settings
  10. import pandas as pd
  11. from utils.hlm_http_request import forward_request
  12. from utils.utils_func import check_path
  13. from sockets.socket_client import socket_manager
  14. from mcu.DeviceControl import DeviceControl
  15. import time, shutil
  16. from sqlalchemy import and_, asc, desc
  17. from functools import partial
  18. from service.deal_image import DealImage
  19. from databases import DeviceConfig, SqlQuery, CRUD, select
  20. from service.run_main import RunMain
  21. import importlib
  22. from service.auto_deal_pics.upload_pic import UploadPic
  23. # from service.AutoDealPics import AutoDealPics
  24. # for plugin in settings.plugins:
  25. # module_path, class_name = plugin.rsplit(".", 1)
  26. # print("module_path", module_path, class_name)
  27. # module = importlib.import_module(module_path)
  28. # getattr(module, class_name)
  29. @app.get("/")
  30. async def index():
  31. # await socket_manager.send_message(msg="测试")
  32. return {"message": "Hello World"}
  33. @app.get("/send_test")
  34. async def index():
  35. data = {"data1": 1, "data2": 2, "data3": 3, "data4": 4}
  36. await socket_manager.send_message(msg="测试", data=data)
  37. return {"message": "Hello World"}
  38. @app.get("/scan_serials", description="扫描可用的设备端口")
  39. async def scanSerials():
  40. """扫描串口"""
  41. ports = list_ports.comports()
  42. print("Scanning", ports)
  43. return {"message": "Hello World"}
  44. @app.get("/test_conndevice")
  45. def test_conndevice():
  46. device_control = DeviceControl()
  47. p_list = []
  48. temp_ports_dict = {}
  49. # while 1:
  50. time.sleep(1)
  51. ports_dict = device_control.scan_serial_port()
  52. temp_ports_dict = ports_dict
  53. if not ports_dict:
  54. # 全部清空 移除所有串口
  55. if p_list:
  56. _p = p_list.pop()
  57. device_control.remove_port(_p)
  58. # continue
  59. if ports_dict:
  60. # print(plist)
  61. for index, _i in enumerate(p_list):
  62. if _i not in ports_dict:
  63. _p = p_list.pop(index)
  64. device_control.remove_port(_p)
  65. for _port_name, _port_value in ports_dict.items():
  66. if _port_name not in p_list:
  67. try:
  68. p_list.append(_port_name)
  69. device_control.add_port_by_linkage(_port_name)
  70. except BaseException as e:
  71. print(
  72. e.__traceback__.tb_frame.f_globals["__file__"]
  73. ) # 发生异常所在的文件
  74. print(e.__traceback__.tb_lineno) # 发生异常所在的行数
  75. print("串口不存在{} {}".format(_port_name, e))
  76. # threading.Thread(target=self.add_port, args=(_port_name, _port_value)).start()
  77. # self.add_port(_p)
  78. @app.api_route(
  79. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  80. )
  81. async def forwardRequest(request: HlmForwardRequest):
  82. """
  83. 转发HTTP请求到目标URL
  84. :param request: FastAPI Request对象
  85. :return: 目标接口的响应
  86. """
  87. try:
  88. if request.method == "GET":
  89. params = request.query_params
  90. elif request.method == "POST":
  91. params = json.dump(request.query_params)
  92. else:
  93. raise UnicornException("仅支持GET和POST方法")
  94. target_url = request.target_url
  95. method = request.method.upper()
  96. headers = request.headers
  97. if not target_url:
  98. raise UnicornException("目标url地址不能为空")
  99. # 调用 hlm_http_request 中的 forward_request 函数
  100. response = forward_request(
  101. target_url, params=params, method=method, headers=headers
  102. )
  103. return response
  104. except requests.RequestException as e:
  105. raise UnicornException(e)
  106. except Exception as e:
  107. raise UnicornException(e)
  108. def fromExcelHandler(params: HandlerDetail):
  109. excel_path = params.excel_path
  110. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  111. handler_result = []
  112. handler_result_folder = ""
  113. if "文件夹名称" not in excel_df.columns:
  114. raise UnicornException("缺失 [文件夹名称] 列")
  115. if "商品货号" not in excel_df.columns:
  116. raise UnicornException("缺失 [商品货号] 列")
  117. for index, row in excel_df.iterrows():
  118. goods_art_no_image_dir = row["文件夹名称"]
  119. goods_art_no = row["商品货号"]
  120. try:
  121. if not goods_art_no:
  122. raise UnicornException("货号不能为空")
  123. token = "Bearer " + params.token
  124. session = SqlQuery()
  125. pr = CRUD(PhotoRecord)
  126. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  127. if not images:
  128. raise UnicornException("没有可用货号数据")
  129. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  130. check_path(image_dir)
  131. for itemImg in images:
  132. if not os.path.exists(
  133. image_dir + "/" + os.path.basename(itemImg.image_path)
  134. ):
  135. shutil.copy(itemImg.image_path, image_dir)
  136. dealImage = DealImage(image_dir)
  137. resFlag, path = dealImage.dealMoveImage(
  138. image_dir=image_dir,
  139. callback_func=None,
  140. goods_art_no=goods_art_no_image_dir,
  141. )
  142. if not resFlag:
  143. raise UnicornException(path)
  144. temp_class = {}
  145. temp_name_list = []
  146. for tempItem in params.temp_list:
  147. temp_class[tempItem.template_id] = tempItem.template_local_classes
  148. temp_name_list.append(tempItem.template_id)
  149. if goods_art_no_image_dir not in path:
  150. path = path + "/" + goods_art_no_image_dir
  151. config_data = {
  152. "image_dir": path,
  153. "image_order": params.template_image_order,
  154. "goods_art_no": goods_art_no,
  155. "is_check_number": False,
  156. "resize_image_view": "后跟",
  157. "cutout_mode": settings.CUTOUT_MODE,
  158. "logo_path": params.logo_path,
  159. "special_goods_art_no_folder_line": "",
  160. "is_use_excel": (
  161. False if params.excel_path == "" else True
  162. ), # 是否使用excel
  163. "excel_path": params.excel_path, # excel路径
  164. "is_check_color_is_all": False,
  165. "cutout_is_pass": True,
  166. "assigned_page_dict": {},
  167. "detail_is_pass": True,
  168. "upload_is_pass": False,
  169. "upload_is_enable": False,
  170. "is_filter": False,
  171. "temp_class": temp_class,
  172. "temp_name": params.temp_name,
  173. "temp_name_list": temp_name_list,
  174. "target_error_folder": f"{path}/软件-生成详情错误",
  175. }
  176. # 动态导入类
  177. temp_class_dict = {}
  178. for key, class_path in config_data["temp_class"].items():
  179. module_path, class_name = class_path.rsplit(".", 1)
  180. module = importlib.import_module(module_path)
  181. cls = getattr(module, class_name)
  182. temp_class_dict[key] = cls
  183. config_data["temp_class"] = temp_class_dict
  184. obj = None
  185. run_main = RunMain(obj, token)
  186. return_data = run_main.check_before_cutout(config_data)
  187. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  188. check_for_detail_first_res = None
  189. if cutout_res == True:
  190. return_data_check_before_detail = run_main.check_before_detail(
  191. config_data
  192. )
  193. print(
  194. "return_data_check_before_detail======> 测试 ==>",
  195. return_data_check_before_detail,
  196. )
  197. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  198. return_data_check_before_detail
  199. )
  200. if isinstance(check_for_detail_first_res, partial):
  201. result = check_for_detail_first_res()
  202. try:
  203. config_data = result["config_data"]
  204. except:
  205. config_data = result
  206. if config_data["sign_text"] == "已结束详情处理":
  207. # at_pic = AutoDealPics()
  208. print("config_data", config_data)
  209. if config_data["upload_is_enable"]:
  210. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  211. check_path(to_deal_dir)
  212. print("to_deal_dir", to_deal_dir)
  213. if os.path.exists(to_deal_dir):
  214. upload_pic = UploadPic(
  215. windows=None,
  216. to_deal_dir=to_deal_dir,
  217. config_data=config_data,
  218. token=token,
  219. )
  220. upload_pic.run()
  221. out_put_dir = config_data["out_put_dir"]
  222. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  223. "\\", "/"
  224. )
  225. handler_result_folder = os.path.dirname(out_put_dir_path)
  226. handler_result.append(
  227. {"goods_art_no": goods_art_no, "success": True, "info": "处理成功"}
  228. )
  229. else:
  230. handler_result.append(
  231. {"goods_art_no": goods_art_no, "success": False, "info": "处理失败"}
  232. )
  233. except Exception as e:
  234. handler_result.append(
  235. {"goods_art_no": goods_art_no, "success": False, "info": str(e)}
  236. )
  237. handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  238. return {
  239. "code": 0,
  240. "msg": "",
  241. "data": {"output_folder": handler_result_folder, "list": handler_result},
  242. }
  243. @app.post("/handle_detail")
  244. async def handle_detail(request: Request, params: HandlerDetail):
  245. goods_art_no_array = params.goods_art_no
  246. handler_result = []
  247. handler_result_folder = ""
  248. if params.excel_path != "" or params.excel_path != None:
  249. return fromExcelHandler(params)
  250. for goods_art_no in goods_art_no_array:
  251. try:
  252. if not goods_art_no:
  253. raise UnicornException("货号不能为空")
  254. token = "Bearer " + params.token
  255. session = SqlQuery()
  256. pr = CRUD(PhotoRecord)
  257. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  258. if not images:
  259. raise UnicornException("没有可用货号数据")
  260. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  261. check_path(image_dir)
  262. for itemImg in images:
  263. if not os.path.exists(
  264. image_dir + "/" + os.path.basename(itemImg.image_path)
  265. ):
  266. shutil.copy(itemImg.image_path, image_dir)
  267. dealImage = DealImage(image_dir)
  268. resFlag, path = dealImage.dealMoveImage(
  269. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  270. )
  271. if not resFlag:
  272. raise UnicornException(path)
  273. temp_class = {}
  274. temp_name_list = []
  275. for tempItem in params.temp_list:
  276. temp_class[tempItem.template_id] = tempItem.template_local_classes
  277. temp_name_list.append(tempItem.template_id)
  278. config_data = {
  279. "image_dir": path,
  280. "image_order": params.template_image_order,
  281. "goods_art_no": goods_art_no,
  282. "is_check_number": False,
  283. "resize_image_view": "后跟",
  284. "cutout_mode": settings.CUTOUT_MODE,
  285. "logo_path": params.logo_path,
  286. "special_goods_art_no_folder_line": "",
  287. "is_use_excel": False if params.excel_path == "" else True, # 是否使用excel
  288. "excel_path": params.excel_path, # excel路径
  289. "is_check_color_is_all": False,
  290. "cutout_is_pass": True,
  291. "assigned_page_dict": {},
  292. "detail_is_pass": True,
  293. "upload_is_pass": False,
  294. "upload_is_enable": False,
  295. "is_filter": False,
  296. "temp_class": temp_class,
  297. "temp_name": params.temp_name,
  298. "temp_name_list": temp_name_list,
  299. "target_error_folder": f"{path}/软件-生成详情错误",
  300. }
  301. # 动态导入类
  302. temp_class_dict = {}
  303. for key, class_path in config_data["temp_class"].items():
  304. module_path, class_name = class_path.rsplit(".", 1)
  305. module = importlib.import_module(module_path)
  306. cls = getattr(module, class_name)
  307. temp_class_dict[key] = cls
  308. config_data["temp_class"] = temp_class_dict
  309. obj = None
  310. run_main = RunMain(obj,token)
  311. return_data = run_main.check_before_cutout(config_data)
  312. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  313. check_for_detail_first_res = None
  314. if cutout_res == True:
  315. return_data_check_before_detail = run_main.check_before_detail(config_data)
  316. print(
  317. "return_data_check_before_detail======> 测试 ==>", return_data_check_before_detail
  318. )
  319. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  320. return_data_check_before_detail
  321. )
  322. if isinstance(check_for_detail_first_res, partial):
  323. result = check_for_detail_first_res()
  324. try:
  325. config_data = result["config_data"]
  326. except:
  327. config_data = result
  328. if config_data["sign_text"] == "已结束详情处理":
  329. # at_pic = AutoDealPics()
  330. print("config_data", config_data)
  331. if config_data["upload_is_enable"]:
  332. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  333. check_path(to_deal_dir)
  334. print("to_deal_dir", to_deal_dir)
  335. if os.path.exists(to_deal_dir):
  336. upload_pic = UploadPic(
  337. windows=None,
  338. to_deal_dir=to_deal_dir,
  339. config_data=config_data,
  340. token=token,
  341. )
  342. upload_pic.run()
  343. out_put_dir = config_data["out_put_dir"]
  344. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace("\\", "/")
  345. handler_result_folder = os.path.dirname(out_put_dir_path)
  346. handler_result.append(
  347. {"goods_art_no": goods_art_no, "success": True, "info": "处理成功"}
  348. )
  349. else:
  350. handler_result.append(
  351. {"goods_art_no": goods_art_no, "success": False, "info": "处理失败"}
  352. )
  353. except Exception as e:
  354. handler_result.append(
  355. {"goods_art_no": goods_art_no, "success": False, "info": str(e)}
  356. )
  357. return {
  358. "code": 0,
  359. "msg": "",
  360. "data": {"output_folder": handler_result_folder, "list": handler_result},
  361. }
  362. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  363. def get_device_configs(params: ModelGetDeviceConfig):
  364. mode_type = params.mode_type
  365. session = SqlQuery()
  366. configModel = CRUD(DeviceConfig)
  367. configList = configModel.read_all(
  368. session,
  369. conditions={"mode_type": mode_type},
  370. order_by="action_index",
  371. ascending=True,
  372. )
  373. return {
  374. "code": 0,
  375. "msg": "",
  376. "data": {"list": configList},
  377. }
  378. @app.post("/device_config_detail", description="获取可执行程序详情")
  379. def get_device_configs(params: ModelGetDeviceConfigDetail):
  380. action_id = params.id
  381. session = SqlQuery()
  382. configModel = CRUD(DeviceConfig)
  383. model = configModel.read(session, conditions={"id": action_id})
  384. if model == None:
  385. return {"code": 1, "msg": "数据不存在", "data": None}
  386. return {"code": 0, "msg": "", "data": model}
  387. @app.post("/remove_config", description="删除一条可执行命令")
  388. def get_device_configs(params: ModelGetDeviceConfigDetail):
  389. action_id = params.id
  390. session = SqlQuery()
  391. configModel = CRUD(DeviceConfig)
  392. model = configModel.read(session, conditions={"id": action_id})
  393. if model == None:
  394. return {"code": 1, "msg": "数据不存在", "data": None}
  395. configModel.delete(session, obj_id=action_id)
  396. return {"code": 0, "msg": "删除成功", "data": None}
  397. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  398. def save_device_config(params: SaveDeviceConfig):
  399. action_id = params.id
  400. session = SqlQuery()
  401. deviceConfig = CRUD(DeviceConfig)
  402. if action_id == None or action_id == 0:
  403. # 走新增逻辑
  404. params.id = None
  405. save_device_config = deviceConfig.create(session, obj_in=params)
  406. else:
  407. model = deviceConfig.read(session, conditions={"id": action_id})
  408. if model == None:
  409. return {"code": 1, "msg": "数据不存在", "data": None}
  410. # 走编辑逻辑
  411. kwargs = params.__dict__
  412. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  413. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  414. @app.post("/reset_config", description="创建或修改一条可执行命令")
  415. def reset_config(params: ModelGetDeviceConfig):
  416. mode_type = params.mode_type
  417. if mode_type == None or mode_type == "":
  418. return {"code": 1, "msg": "参数错误", "data": None}
  419. session = SqlQuery()
  420. deviceConfig = CRUD(DeviceConfig)
  421. res = deviceConfig.deleteConditions(session, conditions={"mode_type": mode_type})
  422. if res is False:
  423. return {"code": 1, "msg": "操作失败", "data": None}
  424. actions = json.load(open("action.json", encoding="utf-8"))
  425. act = []
  426. for item in actions:
  427. if item.get("mode_type") == mode_type:
  428. act.append(item)
  429. batch_insert_device_configs(session, act)
  430. return {"code": 0, "msg": "操作成功", "data": None}
  431. @app.get("/get_photo_records", description="获取拍照记录")
  432. def get_photo_records(page: int = 1, size: int = 5):
  433. session = SqlQuery()
  434. photos = CRUD(PhotoRecord)
  435. statement = (
  436. select(PhotoRecord)
  437. .offset((page - 1) * size)
  438. .limit(size)
  439. .order_by(desc("id"))
  440. .group_by("goods_art_no")
  441. )
  442. list = []
  443. result = session.exec(statement).all()
  444. for item in result:
  445. list_item = photos.read_all(
  446. session, conditions={"goods_art_no": item.goods_art_no}
  447. )
  448. list.append(
  449. {
  450. "goods_art_no": item.goods_art_no,
  451. "action_time": item.create_time,
  452. "items": list_item,
  453. }
  454. )
  455. session.close()
  456. return {
  457. "code": 0,
  458. "msg": "",
  459. "data": {"list": list, "page": page, "size": size},
  460. }
  461. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  462. def get_photo_records(goods_art_no: str = None):
  463. if goods_art_no == None:
  464. return {"code": 1, "msg": "参数错误", "data": None}
  465. session = SqlQuery()
  466. photos = CRUD(PhotoRecord)
  467. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  468. session.close()
  469. return {
  470. "code": 0,
  471. "msg": "",
  472. "data": {"list": items},
  473. }
  474. @app.post("/delect_goods_arts", description="通过货号删除记录")
  475. def delect_goods_arts(params: PhotoRecordDelete):
  476. session = SqlQuery()
  477. photos = CRUD(PhotoRecord)
  478. for item in params.goods_art_nos:
  479. photos.deleteConditions(session, conditions={"goods_art_no": item})
  480. session.close()
  481. return {
  482. "code": 0,
  483. "msg": "操作成功",
  484. "data": None,
  485. }
  486. @app.get("/get_sys_config", description="查询系统配置")
  487. def get_sys_config(key: str = None):
  488. if key == None:
  489. return {"code": 1, "msg": "参数错误", "data": None}
  490. session = SqlQuery()
  491. photos = CRUD(SysConfigs)
  492. item = photos.read(session, conditions={"key": key})
  493. session.close()
  494. return {
  495. "code": 0,
  496. "msg": "",
  497. "data": json.loads(item.value),
  498. }
  499. @app.post("/update_sys_configs", description="创建或修改系统配置")
  500. def save_sys_configs(params: SysConfigParams):
  501. session = SqlQuery()
  502. sysConfig = CRUD(SysConfigs)
  503. model = sysConfig.read(session, conditions={"key": params.key})
  504. if model == None:
  505. return {"code": 1, "msg": "配置不存在", "data": None}
  506. # 走编辑逻辑
  507. kwargs = params.__dict__
  508. save_device_config = sysConfig.updateConditions(
  509. session, conditions={"key": params.key}, **kwargs
  510. )
  511. return {"code": 0, "msg": "操作成功", "data": save_device_config}