api.py 33 KB

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