mom上传图片
This commit is contained in:
68
upload_pict_mom.py
Normal file
68
upload_pict_mom.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import requests
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.events import FileSystemEventHandler
|
||||
|
||||
# 加载配置
|
||||
with open("config_mom.json", 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__":
|
||||
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()
|
Reference in New Issue
Block a user