api.py 35 KB

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