api.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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, datetime
  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, os
  16. from sqlalchemy import and_, asc, desc
  17. from functools import partial
  18. from service.deal_image import DealImage
  19. from databases import DeviceConfig, SysConfigs, SqlQuery, CRUD, select, DeviceConfigTabs
  20. from service.run_main import RunMain
  21. import importlib
  22. from service.auto_deal_pics.upload_pic import UploadPic
  23. from service.OnePicTest import OnePicTest
  24. from service.base import check_move_goods_art_no_folder
  25. import hashlib
  26. import win32api, win32gui, win32con
  27. from win32gui import EnumWindows, GetWindowText
  28. # from service.AutoDealPics import AutoDealPics
  29. # for plugin in settings.plugins:
  30. # module_path, class_name = plugin.rsplit(".", 1)
  31. # print("module_path", module_path, class_name)
  32. # module = importlib.import_module(module_path)
  33. # getattr(module, class_name)
  34. def calculate_md5(filepath):
  35. # 打开文件,以二进制只读模式打开
  36. with open(filepath, "rb") as f:
  37. # 创建MD5哈希对象
  38. md5hash = hashlib.md5()
  39. # 循环读取文件的内容并更新哈希对象
  40. for chunk in iter(lambda: f.read(4096), b""):
  41. md5hash.update(chunk)
  42. # 返回MD5哈希的十六进制表示
  43. return md5hash.hexdigest()
  44. @app.get("/")
  45. async def index():
  46. # await socket_manager.send_message(msg="测试")
  47. return {"message": "Hello World"}
  48. @app.get("/scan_serials", description="扫描可用的设备端口")
  49. async def scanSerials():
  50. """扫描串口"""
  51. ports = list_ports.comports()
  52. print("Scanning", ports)
  53. return {"message": "Hello World"}
  54. @app.api_route(
  55. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  56. )
  57. async def forwardRequest(request: HlmForwardRequest):
  58. """
  59. 转发HTTP请求到目标URL
  60. :param request: FastAPI Request对象
  61. :return: 目标接口的响应
  62. """
  63. try:
  64. if request.method == "GET":
  65. params = request.query_params
  66. elif request.method == "POST":
  67. params = json.dump(request.query_params)
  68. else:
  69. raise UnicornException("仅支持GET和POST方法")
  70. target_url = request.target_url
  71. method = request.method.upper()
  72. headers = request.headers
  73. if not target_url:
  74. raise UnicornException("目标url地址不能为空")
  75. # 调用 hlm_http_request 中的 forward_request 函数
  76. response = forward_request(
  77. target_url, params=params, method=method, headers=headers
  78. )
  79. return response
  80. except requests.RequestException as e:
  81. raise UnicornException(e)
  82. except Exception as e:
  83. raise UnicornException(e)
  84. def fromExcelHandler(params: HandlerDetail):
  85. excel_path = params.excel_path
  86. token = "Bearer " + params.token
  87. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  88. handler_result = []
  89. handler_result_folder = ""
  90. if "文件夹名称" not in excel_df.columns:
  91. raise UnicornException("缺失 [文件夹名称] 列")
  92. if "商品货号" not in excel_df.columns:
  93. raise UnicornException("缺失 [商品货号] 列")
  94. if "款号" not in excel_df.columns:
  95. raise UnicornException("缺失 [款号] 列")
  96. goods_art_dirs = excel_df.groupby(excel_df["款号"])
  97. obj = None
  98. run_main = RunMain(obj, token)
  99. temp_class = {}
  100. # 可用模板列表-需要导包
  101. temp_name_list = []
  102. for tempItem in params.temp_list:
  103. temp_class[tempItem.template_id] = tempItem.template_local_classes
  104. temp_name_list.append(tempItem.template_id)
  105. # 抠图时用到的货号列表,与生成详情图有所区别
  106. goods_art_no_arrays = []
  107. # # 详情图生成需要对同款商品进行分组,保证详情图可以生成多个色
  108. goods_art_no_group_arrays = []
  109. for _, goods_row in excel_df.iterrows():
  110. goods_art_no = str(goods_row["商品货号"])
  111. goods_art_no_arrays.append(goods_art_no)
  112. goods_no = str(goods_row["款号"])
  113. a001_df = goods_art_dirs.get_group(goods_no)
  114. goods_art_groups = a001_df["商品货号"].tolist()
  115. if goods_art_groups in goods_art_no_group_arrays:
  116. continue
  117. goods_art_no_group_arrays.append(goods_art_groups)
  118. limit_path = "output/{}".format(
  119. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  120. )
  121. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  122. move_folder_array = check_move_goods_art_no_folder(
  123. "output", goods_art_no_arrays, limit_path
  124. )
  125. for index, row in excel_df.iterrows():
  126. goods_art_no_image_dir = str(row["文件夹名称"])
  127. goods_art_no = str(row["商品货号"])
  128. print("货号数据", goods_art_no)
  129. if not goods_art_no:
  130. raise UnicornException("货号不能为空")
  131. session = SqlQuery()
  132. pr = CRUD(PhotoRecord)
  133. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  134. if not images:
  135. raise UnicornException("没有可用货号数据")
  136. # 货号目录不存在再去进行移动和创建操作
  137. if move_folder_array.get(goods_art_no) == None:
  138. image_dir = "{}/data/".format(os.getcwd()).replace(
  139. "\\", "/"
  140. )
  141. check_path(image_dir)
  142. for idx, itemImg in enumerate(images):
  143. if itemImg.image_path == "" or itemImg.image_path == None:
  144. raise UnicornException(
  145. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  146. )
  147. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  148. if not os.path.exists(
  149. image_dir + "/" + os.path.basename(new_file_name)
  150. ):
  151. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  152. dealImage = DealImage(image_dir)
  153. resFlag, path = dealImage.dealMoveImage(
  154. image_dir=image_dir,
  155. callback_func=None,
  156. goods_art_no=goods_art_no_image_dir,
  157. )
  158. if not resFlag:
  159. raise UnicornException(path)
  160. shutil.rmtree(image_dir)
  161. # path = os.path.dirname(path)
  162. config_data = {
  163. "image_dir": limit_path, # 这个目录作为本次生成的图片目录非常重要 例:./output/当前日期
  164. "image_order": params.template_image_order,
  165. "goods_art_no": goods_art_no,
  166. "goods_art_nos": goods_art_no_arrays,
  167. "is_check_number": False,
  168. "resize_image_view": "后跟",
  169. "cutout_mode": settings.CUTOUT_MODE,
  170. "logo_path": params.logo_path,
  171. "special_goods_art_no_folder_line": "",
  172. "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  173. "excel_path": params.excel_path, # excel路径
  174. "is_check_color_is_all": False,
  175. "cutout_is_pass": True,
  176. "assigned_page_dict": {},
  177. "detail_is_pass": True,
  178. "upload_is_pass": False,
  179. "upload_is_enable": False,
  180. "is_filter": False,
  181. "temp_class": temp_class,
  182. "temp_name": params.temp_name,
  183. "temp_name_list": temp_name_list,
  184. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  185. "success_handler": [],
  186. }
  187. # 动态导入类
  188. temp_class_dict = {}
  189. for key, class_path in config_data["temp_class"].items():
  190. module_path, class_name = class_path.rsplit(".", 1)
  191. module = importlib.import_module(module_path)
  192. cls = getattr(module, class_name)
  193. temp_class_dict[key] = cls
  194. config_data["temp_class"] = temp_class_dict
  195. # 此处对抠图进行批量处理,保证所有的图片在生成详情图之前已经完成抠图,以保证详情图生成的效率
  196. return_data = run_main.check_before_cutout(config_data)
  197. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  198. check_for_detail_first_res = None
  199. try:
  200. if cutout_res:
  201. return_data_check_before_detail = run_main.check_before_detail(config_data)
  202. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  203. return_data_check_before_detail
  204. )
  205. if isinstance(check_for_detail_first_res, partial):
  206. result = check_for_detail_first_res()
  207. try:
  208. config_data = result["config_data"]
  209. except:
  210. config_data = result
  211. if config_data["sign_text"] == "已结束详情处理":
  212. print("config_data", config_data)
  213. if config_data["upload_is_enable"]:
  214. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  215. check_path(to_deal_dir)
  216. print("to_deal_dir", to_deal_dir)
  217. if os.path.exists(to_deal_dir):
  218. upload_pic = UploadPic(
  219. windows=None,
  220. to_deal_dir=to_deal_dir,
  221. config_data=config_data,
  222. token=token,
  223. )
  224. upload_pic.run()
  225. out_put_dir = config_data.get("out_put_dir")
  226. if out_put_dir == None:
  227. handler_result_folder = ""
  228. if len(config_data["success_handler"]) > 0:
  229. for good_art in config_data["success_handler"]:
  230. handler_result.append(good_art)
  231. else:
  232. for good_art in goods_art_no_arrays:
  233. handler_result.append(
  234. {
  235. "goods_art_no": good_art,
  236. "success": False,
  237. "info": "处理失败",
  238. }
  239. )
  240. else:
  241. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  242. "\\", "/"
  243. )
  244. handler_result_folder = os.path.dirname(out_put_dir_path)
  245. if len(config_data["success_handler"])==0:
  246. for good_art in goods_art_no_arrays:
  247. handler_result.append(
  248. {"goods_art_no": good_art, "success": False, "info": "处理失败"}
  249. )
  250. else:
  251. handler_result = config_data["success_handler"]
  252. else:
  253. for good_art in goods_art_no_arrays:
  254. handler_result.append(
  255. {"goods_art_no": good_art, "success": False, "info": "处理失败"}
  256. )
  257. except Exception as e:
  258. for good_art in goods_art_no_arrays:
  259. handler_result.append(
  260. {"goods_art_no": good_art, "success": False, "info": str(e)}
  261. )
  262. handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  263. return {
  264. "code": 0,
  265. "msg": "",
  266. "data": {"output_folder": handler_result_folder, "list": handler_result},
  267. }
  268. def group_by_style_number(data):
  269. result = {}
  270. for goods_id, info in data.items():
  271. style_number = info["款号"]
  272. if style_number not in result:
  273. result[style_number] = []
  274. result[style_number].append(goods_id)
  275. return result
  276. @app.post("/handle_detail")
  277. async def handle_detail(request: Request, params: HandlerDetail):
  278. obj = None
  279. token = "Bearer " + params.token
  280. run_main = RunMain(obj, token)
  281. goods_art_no_arrays = params.goods_art_no
  282. is_only_cutout = params.is_only_cutout
  283. handler_result = []
  284. handler_result_folder = ""
  285. if is_only_cutout == 1:
  286. # 如果是仅抠图模式,避免进入到excel模式
  287. params.excel_path = ""
  288. if params.excel_path != "" and params.excel_path != None:
  289. return fromExcelHandler(params)
  290. # goods_art_list = run_main.data_mode_generate_detail.get_goods_art_no_info(
  291. # goods_art_list=goods_art_no_arrays
  292. # )
  293. # goods_art_nos = []
  294. # goods_art_list_dict = group_by_style_number(goods_art_list)
  295. path = ""
  296. limit_path = "output/{}".format(
  297. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  298. )
  299. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  300. move_folder_array = check_move_goods_art_no_folder(
  301. "output", goods_art_no_arrays, limit_path
  302. )
  303. for goods_art_no in goods_art_no_arrays:
  304. if not goods_art_no:
  305. raise UnicornException("货号不能为空")
  306. session = SqlQuery()
  307. pr = CRUD(PhotoRecord)
  308. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  309. if not images:
  310. raise UnicornException("没有可用货号数据")
  311. if is_only_cutout != 1:
  312. detail_counts = len(params.template_image_order.split(","))
  313. image_counts = len(images)
  314. if image_counts < detail_counts:
  315. raise UnicornException(
  316. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  317. )
  318. if move_folder_array.get(goods_art_no) == None:
  319. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  320. check_path(image_dir)
  321. for idx, itemImg in enumerate(images):
  322. if itemImg.image_path == "" or itemImg.image_path == None:
  323. raise UnicornException(
  324. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  325. )
  326. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  327. if not os.path.exists(
  328. image_dir + "/" + os.path.basename(new_file_name)
  329. ):
  330. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  331. dealImage = DealImage(image_dir)
  332. resFlag, path = dealImage.dealMoveImage(
  333. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  334. )
  335. if not resFlag:
  336. raise UnicornException(path)
  337. # try:
  338. temp_class = {}
  339. temp_name_list = []
  340. for tempItem in params.temp_list:
  341. temp_class[tempItem.template_id] = tempItem.template_local_classes
  342. temp_name_list.append(tempItem.template_id)
  343. config_data = {
  344. "image_dir": limit_path,
  345. "image_order": (
  346. "俯视,侧视,后跟,鞋底,内里"
  347. if params.template_image_order == None
  348. or params.template_image_order == ""
  349. else params.template_image_order
  350. ),
  351. "goods_art_no": "",
  352. "goods_art_nos": goods_art_no_arrays,
  353. "is_check_number": False,
  354. "resize_image_view": "后跟",
  355. "cutout_mode": settings.CUTOUT_MODE,
  356. "logo_path": params.logo_path,
  357. "special_goods_art_no_folder_line": "",
  358. "is_use_excel": False, # 是否使用excel
  359. "excel_path": "", # excel路径
  360. "is_check_color_is_all": False,
  361. "cutout_is_pass": True,
  362. "assigned_page_dict": {},
  363. "detail_is_pass": True,
  364. "upload_is_pass": False,
  365. "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  366. "is_filter": False,
  367. "temp_class": temp_class,
  368. "temp_name": params.temp_name,
  369. "temp_name_list": temp_name_list,
  370. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  371. "success_handler": [],
  372. }
  373. print("image_dir=====>>>>>", config_data["image_dir"])
  374. # 动态导入类
  375. temp_class_dict = {}
  376. for key, class_path in config_data["temp_class"].items():
  377. module_path, class_name = class_path.rsplit(".", 1)
  378. module = importlib.import_module(module_path)
  379. cls = getattr(module, class_name)
  380. temp_class_dict[key] = cls
  381. config_data["temp_class"] = temp_class_dict
  382. return_data = run_main.check_before_cutout(config_data)
  383. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  384. check_for_detail_first_res = None
  385. if cutout_res == True:
  386. sys_path = format(os.getcwd()).replace("\\", "/")
  387. handler_result_folder = f"{sys_path}/{limit_path}"
  388. for goods_art_item in goods_art_no_arrays:
  389. handler_result.append(
  390. {
  391. "goods_art_no": goods_art_item,
  392. "success": True,
  393. "info": "处理成功",
  394. }
  395. )
  396. if is_only_cutout == 1:
  397. return {
  398. "code": 0,
  399. "msg": "",
  400. "data": {"output_folder": handler_result_folder, "list": handler_result},
  401. }
  402. handler_result = []
  403. try:
  404. return_data_check_before_detail = run_main.check_before_detail(config_data)
  405. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  406. return_data_check_before_detail
  407. )
  408. if isinstance(check_for_detail_first_res, partial):
  409. result = check_for_detail_first_res()
  410. try:
  411. config_data = result["config_data"]
  412. except:
  413. config_data = result
  414. if config_data["sign_text"] == "已结束详情处理":
  415. # at_pic = AutoDealPics()
  416. print("config_data", config_data)
  417. # if config_data["upload_is_enable"]:
  418. # to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  419. # check_path(to_deal_dir)
  420. # print("to_deal_dir", to_deal_dir)
  421. # if os.path.exists(to_deal_dir):
  422. # upload_pic = UploadPic(
  423. # windows=None,
  424. # to_deal_dir=to_deal_dir,
  425. # config_data=config_data,
  426. # token=token,
  427. # )
  428. # upload_pic.run()
  429. out_put_dir = config_data.get("out_put_dir")
  430. if out_put_dir == None:
  431. handler_result_folder = ""
  432. if len(config_data["success_handler"]) > 0:
  433. for good_art in config_data["success_handler"]:
  434. handler_result.append(good_art)
  435. else:
  436. for good_art in goods_art_no_arrays:
  437. handler_result.append(
  438. {
  439. "goods_art_no": good_art,
  440. "success": False,
  441. "info": "处理失败",
  442. }
  443. )
  444. else:
  445. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  446. "\\", "/"
  447. )
  448. handler_result_folder = os.path.dirname(out_put_dir_path)
  449. if len(config_data["success_handler"]) == 0:
  450. for good_art in goods_art_no_arrays:
  451. handler_result.append(
  452. {
  453. "goods_art_no": good_art,
  454. "success": False,
  455. "info": "处理失败",
  456. }
  457. )
  458. else:
  459. handler_result = config_data["success_handler"]
  460. else:
  461. handler_result.append(
  462. {"goods_art_no": "", "success": False, "info": "处理失败"}
  463. )
  464. except Exception as e:
  465. print(e.__traceback__.tb_frame.f_globals["__file__"]) # 发生异常所在的文件
  466. print(e.__traceback__.tb_lineno) # 发生异常所在的行数
  467. handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  468. return {
  469. "code": 0,
  470. "msg": "",
  471. "data": {"output_folder": handler_result_folder, "list": handler_result},
  472. }
  473. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  474. def get_device_tabs(type: int):
  475. session = SqlQuery()
  476. statement = (
  477. select(DeviceConfigTabs)
  478. .where(DeviceConfigTabs.mode_type == type)
  479. .order_by(asc("id"))
  480. )
  481. result = session.exec(statement).all()
  482. session.close()
  483. sys = CRUD(SysConfigs)
  484. action_configs = sys.read(session, conditions={"key": "action_configs"})
  485. session.close()
  486. return {
  487. "code": 0,
  488. "msg": "",
  489. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  490. }
  491. @app.post("/update_tab_name", description="更改tab名称")
  492. def update_tab_name(params: DeviceConfigTabsReq):
  493. if params.mode_name == "":
  494. return {"code": 1, "msg": "名称不能为空", "data": {}}
  495. session = SqlQuery()
  496. tabModel = CRUD(DeviceConfigTabs)
  497. kwargs = {"mode_name": params.mode_name}
  498. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  499. session.close()
  500. return {
  501. "code": 0,
  502. "msg": "",
  503. "data": None,
  504. }
  505. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  506. def get_device_configs(params: ModelGetDeviceConfig):
  507. tab_id = params.tab_id
  508. session = SqlQuery()
  509. configModel = CRUD(DeviceConfig)
  510. configList = configModel.read_all(
  511. session,
  512. conditions={"tab_id": tab_id},
  513. order_by="action_index",
  514. ascending=True,
  515. )
  516. return {
  517. "code": 0,
  518. "msg": "",
  519. "data": {"list": configList},
  520. }
  521. @app.post("/device_config_detail", description="获取可执行程序详情")
  522. def device_config_detail(params: ModelGetDeviceConfigDetail):
  523. action_id = params.id
  524. session = SqlQuery()
  525. configModel = CRUD(DeviceConfig)
  526. model = configModel.read(session, conditions={"id": action_id})
  527. if model == None:
  528. return {"code": 1, "msg": "数据不存在", "data": None}
  529. return {"code": 0, "msg": "", "data": model}
  530. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  531. def device_config_detail_query():
  532. # tab_id = params.tab_id
  533. # action_name = params.action_name
  534. session = SqlQuery()
  535. sys = CRUD(SysConfigs)
  536. action_configs = sys.read(session, conditions={"key": "action_configs"})
  537. action_configs_value = json.loads(action_configs.value)
  538. left_config = action_configs_value.get("left")
  539. configModel = CRUD(DeviceConfig)
  540. model = configModel.read(
  541. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  542. )
  543. if model == None:
  544. model = configModel.read(session, conditions={"tab_id": left_config})
  545. return {"code": 0, "msg": "", "data": model}
  546. @app.post("/remove_config", description="删除一条可执行命令")
  547. def get_device_configs(params: ModelGetDeviceConfigDetail):
  548. action_id = params.id
  549. session = SqlQuery()
  550. configModel = CRUD(DeviceConfig)
  551. model = configModel.read(session, conditions={"id": action_id})
  552. if model == None:
  553. return {"code": 1, "msg": "数据不存在", "data": None}
  554. if model.is_system == True:
  555. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  556. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  557. if len(configArray) == 1:
  558. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  559. configModel.delete(session, obj_id=action_id)
  560. return {"code": 0, "msg": "删除成功", "data": None}
  561. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  562. def save_device_config(params: SaveDeviceConfig):
  563. action_id = params.id
  564. session = SqlQuery()
  565. deviceConfig = CRUD(DeviceConfig)
  566. if action_id == None or action_id == 0:
  567. # 走新增逻辑
  568. params.id = None
  569. save_device_config = deviceConfig.create(session, obj_in=params)
  570. else:
  571. model = deviceConfig.read(session, conditions={"id": action_id})
  572. if model == None:
  573. return {"code": 1, "msg": "数据不存在", "data": None}
  574. # 走编辑逻辑
  575. kwargs = params.__dict__
  576. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  577. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  578. @app.post("/reset_config", description="创建或修改一条可执行命令")
  579. def reset_config(params: ModelGetDeviceConfig):
  580. tab_id = params.tab_id
  581. if tab_id == None or tab_id == "":
  582. return {"code": 1, "msg": "参数错误", "data": None}
  583. session = SqlQuery()
  584. deviceConfig = CRUD(DeviceConfig)
  585. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  586. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  587. if res is False:
  588. return {"code": 1, "msg": "操作失败", "data": None}
  589. actions = json.load(open("action.json", encoding="utf-8"))
  590. for data in actions:
  591. data["tab_id"] = tab_id
  592. data["is_system"] = first_config.is_system
  593. device_config = DeviceConfig(**data)
  594. session.add(device_config)
  595. session.commit()
  596. # session.close()
  597. return {"code": 0, "msg": "操作成功", "data": None}
  598. @app.get("/get_photo_records", description="获取拍照记录")
  599. def get_photo_records(page: int = 1, size: int = 5):
  600. session = SqlQuery()
  601. # photos = CRUD(PhotoRecord)
  602. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  603. statement = (
  604. select(PhotoRecord)
  605. .offset((page - 1) * size)
  606. .limit(size)
  607. .order_by(desc("id"))
  608. .group_by("goods_art_no")
  609. )
  610. list = []
  611. result = session.exec(statement).all()
  612. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  613. join_conditions = [
  614. {
  615. "model": DeviceConfig,
  616. "on": PhotoRecord.action_id == DeviceConfig.id,
  617. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  618. }
  619. ]
  620. for item in result:
  621. query = (
  622. select(PhotoRecord, DeviceConfig.action_name)
  623. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  624. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  625. )
  626. list_item = session.exec(query).mappings().all()
  627. list.append(
  628. {
  629. "goods_art_no": item.goods_art_no,
  630. "action_time": item.create_time,
  631. "items": list_item,
  632. }
  633. )
  634. # session.close()
  635. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  636. return {
  637. "code": 0,
  638. "msg": "",
  639. "data": {"list": list, "page": page, "size": size},
  640. }
  641. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  642. def get_last_photo_record():
  643. session = SqlQuery()
  644. statement = (
  645. select(PhotoRecord)
  646. .where(PhotoRecord.image_path != None)
  647. .order_by(desc("photo_create_time"))
  648. )
  649. result = session.exec(statement).first()
  650. # session.close()
  651. return {
  652. "code": 0,
  653. "msg": "",
  654. "data": result,
  655. }
  656. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  657. def get_photo_record_detail(goods_art_no: str = None):
  658. if goods_art_no == None:
  659. return {"code": 1, "msg": "参数错误", "data": None}
  660. session = SqlQuery()
  661. photos = CRUD(PhotoRecord)
  662. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  663. # session.close()
  664. return {
  665. "code": 0,
  666. "msg": "",
  667. "data": {"list": items},
  668. }
  669. @app.post("/delect_goods_arts", description="通过货号删除记录")
  670. def delect_goods_arts(params: PhotoRecordDelete):
  671. session = SqlQuery()
  672. photos = CRUD(PhotoRecord)
  673. for item in params.goods_art_nos:
  674. photos.deleteConditions(session, conditions={"goods_art_no": item})
  675. # session.close()
  676. return {
  677. "code": 0,
  678. "msg": "操作成功",
  679. "data": None,
  680. }
  681. @app.get("/get_sys_config", description="查询系统配置")
  682. def get_sys_config(key: str = None):
  683. if key == None:
  684. return {"code": 1, "msg": "参数错误", "data": None}
  685. session = SqlQuery()
  686. photos = CRUD(SysConfigs)
  687. item = photos.read(session, conditions={"key": key})
  688. # session.close()
  689. return {
  690. "code": 0,
  691. "msg": "",
  692. "data": json.loads(item.value),
  693. }
  694. @app.post("/update_left_right_config", description="更新左右脚配置")
  695. def update_left_right_config(params: LeftRightParams):
  696. session = SqlQuery()
  697. sysConfig = CRUD(SysConfigs)
  698. model = sysConfig.read(session, conditions={"key": "action_configs"})
  699. if model == None:
  700. return {"code": 1, "msg": "配置不存在", "data": None}
  701. config_value = json.loads(model.value)
  702. config_value[params.type] = params.id
  703. update_value = json.dumps(config_value)
  704. # 走编辑逻辑
  705. kwargs = {"key": "action_configs", "value": update_value}
  706. save_device_config = sysConfig.updateConditions(
  707. session, conditions={"key": "action_configs"}, **kwargs
  708. )
  709. return {"code": 0, "msg": "操作成功", "data": None}
  710. @app.post("/update_record", description="更新拍照记录")
  711. def update_record(params: RecordUpdate):
  712. session = SqlQuery()
  713. photoRecord = CRUD(PhotoRecord)
  714. model = photoRecord.read(session, conditions={"id": params.id})
  715. if model == None:
  716. return {"code": 1, "msg": "记录不存在", "data": None}
  717. kwargs = params.__dict__
  718. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  719. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  720. @app.post("/update_sys_configs", description="创建或修改系统配置")
  721. def save_sys_configs(params: SysConfigParams):
  722. session = SqlQuery()
  723. sysConfig = CRUD(SysConfigs)
  724. model = sysConfig.read(session, conditions={"key": params.key})
  725. if model == None:
  726. return {"code": 1, "msg": "配置不存在", "data": None}
  727. # 走编辑逻辑
  728. kwargs = params.__dict__
  729. save_device_config = sysConfig.updateConditions(
  730. session, conditions={"key": params.key}, **kwargs
  731. )
  732. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  733. @app.post("/create_main_image", description="创建主图测试")
  734. def create_main_image(params: MaineImageTest):
  735. file_path = params.file_path
  736. onePic = OnePicTest(pic_path=file_path)
  737. main_out_path = onePic.HandlerMainImage()
  738. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  739. def insertEmptyLogoList(session):
  740. """插入空logo列表"""
  741. data = {"key": "logo_configs", "value": "[]"}
  742. config = SysConfigs(**data)
  743. session.add(config)
  744. session.commit()
  745. session.close()
  746. item = SysConfigs()
  747. item.key = "logo_configs"
  748. item.value = "[]"
  749. return item
  750. @app.get("/logo_list", description="logo列表")
  751. def logo_list():
  752. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  753. check_path(logo_dir)
  754. logo_files = os.listdir(logo_dir)
  755. logo_list = []
  756. for logoItem in logo_files:
  757. logo_list.append(f"{logo_dir}{logoItem}")
  758. return {"code": 0, "msg": "操作成功", "data": logo_list}
  759. @app.post("/add_logo", description="添加logo")
  760. def add_logo(params: LogoParams):
  761. logo_path = params.logo_path.replace("\\", "/")
  762. session = SqlQuery()
  763. sysConfig = CRUD(SysConfigs)
  764. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  765. if item == None:
  766. item = insertEmptyLogoList(session)
  767. if os.path.isfile(logo_path) == False:
  768. return {"code": 1, "msg": "logo文件不存在", "data": None}
  769. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  770. check_path(logo_dir)
  771. fpath, fname = os.path.split(logo_path)
  772. logo_path_info = logo_dir + fname
  773. shutil.copy(logo_path, logo_path_info) # 复制文件
  774. logo_files = os.listdir(logo_dir)
  775. logo_list = []
  776. for logoItem in logo_files:
  777. logo_list.append(f"{logo_dir}{logoItem}")
  778. return {
  779. "code": 0,
  780. "msg": "",
  781. "data": {"logo": logo_path_info},
  782. }
  783. @app.post("/delete_logo", description="删除logo")
  784. def delete_logo(params: LogoParamsupdate):
  785. logo_path = params.path
  786. if os.path.isfile(logo_path) == False:
  787. return {"code": 1, "msg": "logo文件不存在", "data": None}
  788. os.remove(logo_path)
  789. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  790. check_path(logo_dir)
  791. logo_files = os.listdir(logo_dir)
  792. logo_list = []
  793. for logoItem in logo_files:
  794. logo_list.append(f"{logo_dir}{logoItem}")
  795. return {"code": 0, "msg": "操作成功", "data": logo_list}
  796. @app.post("/close_other_window", description="关闭窗口")
  797. def close_other_window():
  798. hwnd_list = []
  799. def callback(hwnd, _):
  800. title = GetWindowText(hwnd)
  801. if title == "digiCamControl by Duka Istvan":
  802. hwnd_list.append(hwnd)
  803. EnumWindows(callback, None)
  804. if hwnd_list:
  805. hwnd = hwnd_list[0]
  806. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  807. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  808. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}