72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
import os
|
||
import time
|
||
import json
|
||
import requests
|
||
from watchdog.observers import Observer
|
||
from watchdog.events import FileSystemEventHandler
|
||
|
||
# 加载配置
|
||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||
config_path = os.path.join(current_dir, 'config_mom.json')
|
||
with open(config_path, encoding="utf-8") as f:
|
||
config = json.load(f)
|
||
|
||
MOM_UPLOAD_URL = f"{config['mom_prefix']}/cams-service/openapi/hotwater/file/upload"
|
||
OPNO = config["opNo"]
|
||
WATCH_FOLDERS = config["watch_folders"]
|
||
|
||
|
||
def extract_sn(filename: str) -> str:
|
||
"""取文件名前 22 位作为 SN;不足 22 位则整个文件名返回"""
|
||
name, _ = os.path.splitext(filename) # 去掉扩展名
|
||
return name[:22]
|
||
|
||
|
||
def upload_image(file_path: str) -> None:
|
||
filename = os.path.basename(file_path)
|
||
sn = extract_sn(filename)
|
||
# 构造三个独立的 multipart 字段
|
||
multipart_fields = {
|
||
"opNo": (None, OPNO), # 普通文本字段
|
||
"sn": (None, sn), # 普通文本字段
|
||
"file": (filename, open(file_path, "rb"), "image/jpeg")
|
||
}
|
||
try:
|
||
resp = requests.post(
|
||
MOM_UPLOAD_URL,
|
||
files=multipart_fields,
|
||
timeout=30
|
||
)
|
||
print(f"[上传] {filename} → {resp.status_code} {resp.text}")
|
||
except Exception as e:
|
||
print(f"[上传失败] {filename} → {e}")
|
||
|
||
|
||
class ImageHandler(FileSystemEventHandler):
|
||
def on_created(self, event):
|
||
if not event.is_directory:
|
||
ext = os.path.splitext(event.src_path)[1].lower()
|
||
time.sleep(0.5) # 等待文件写完
|
||
upload_image(event.src_path)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# pyinstaller upload_pict_mom.py --add-data config_mom.json:.
|
||
# 给mom上传图片
|
||
for folder in WATCH_FOLDERS:
|
||
os.makedirs(folder, exist_ok=True)
|
||
|
||
event_handler = ImageHandler()
|
||
observer = Observer()
|
||
|
||
for folder in WATCH_FOLDERS:
|
||
observer.schedule(event_handler, folder, recursive=False)
|
||
print(f"[监控启动] {os.path.abspath(folder)}")
|
||
|
||
observer.start()
|
||
try:
|
||
while True:
|
||
time.sleep(1)
|
||
except KeyboardInterrupt:
|
||
observer.stop()
|
||
observer.join() |