Browse Source

临时提交

zhangyh 9 months ago
parent
commit
76e1eb8cf2
5 changed files with 177 additions and 11 deletions
  1. 4 2
      python/config.ini
  2. 25 9
      python/index.py
  3. 85 0
      python/service/init_load_source.py
  4. 2 0
      python/settings.py
  5. 61 0
      python/utils/utils_func.py

+ 4 - 2
python/config.ini

@@ -4,7 +4,7 @@ app_name=智慧拍-后端应用
 # 应用版本号
 version=1.0.0
 # 应用host地址
-host=10.56.42.176
+host=127.0.0.1
 # 应用服务启动名称
 app_run=api:app
 # 端口号
@@ -19,4 +19,6 @@ log_file_name=app.log
 #最大字节数
 max_bytes=102400 
 #备份数量
-backup_counts=3 
+backup_counts=3
+# 地址
+hlm_host=https://dev2.pubdata.cn

+ 25 - 9
python/index.py

@@ -1,3 +1,4 @@
+import asyncio
 import sys
 import uvicorn
 import signal
@@ -8,6 +9,8 @@ import uvicorn.protocols.http.auto
 import uvicorn.protocols.websockets.auto
 import uvicorn.lifespan.on
 from multiprocessing import Process, freeze_support
+from service.init_load_source import init_load_source
+
 
 def handle_shutdown(signum, frame):
     """关闭系统应用服务"""
@@ -16,18 +19,31 @@ def handle_shutdown(signum, frame):
     loop.call_soon_threadsafe(loop.stop)
     sys.exit(0)
 
-if __name__ == "__main__":
-    signal.signal(signal.SIGINT, handle_shutdown)
-    signal.signal(signal.SIGTERM, handle_shutdown)
-    # 控制台默认关闭输出信息,如果想要查看控制台输出,请单独启动服务 npm run dev-python
-    print("python server is running at port:", PORT)
-    # uvicorn会多创建一个进程,并且stdio独立于控制台,如果(开发时)出现进程没有关闭,可尝试关闭终端
-    print("python server is running at port:", APP_RUN)
-    isDebug = True if IS_DEBUG == "true" else False
-    uvicorn.run(
+async def run_server():
+    # 启动uvicorn服务器
+    config = uvicorn.Config(
         APP_RUN,
         host=APP_HOST,
         port=int(PORT),
         reload=isDebug,
         workers=int(APP_WORKS),
     )
+    server = uvicorn.Server(config)
+    await server.serve()
+
+async def main():
+    # 创建后台任务
+    task = asyncio.create_task(init_load_source().load_source())
+    # 启动服务器
+    print(">>>>>>>>>>>>>>>>>>>>>>>>>>")
+    await run_server()
+
+
+
+if __name__ == "__main__":
+    signal.signal(signal.SIGINT, handle_shutdown)
+    signal.signal(signal.SIGTERM, handle_shutdown)
+    print("python server is running at port:", PORT)
+    print("python server is running at port:", APP_RUN)
+    isDebug = True if IS_DEBUG == "true" else False
+    asyncio.run(main())

+ 85 - 0
python/service/init_load_source.py

@@ -0,0 +1,85 @@
+import asyncio
+import json
+import time
+from settings import HLM_HOST
+import requests
+import os
+from utils.utils_func import get_md5,get_modified_time,compare_two_times,download_file
+
+
+class init_load_source:
+
+    def __init__(self):
+        pass
+
+    async def load_source(self):
+        # asyncio.sleep()
+        # await self.down_resouce()
+
+        for i in range(100):
+            print(1)
+            await  asyncio.sleep(1)
+
+
+
+    async def down_resouce(self):
+        response_data = self.get_update_file()
+        if response_data:
+            for relative_file_path, value in response_data.items():
+                file_path = "{}\{}".format(os.getcwd(), relative_file_path)
+                if os.path.exists(file_path):
+                    file_md5 = get_md5(file_path)
+                    if file_md5 != value["file_md5"]:
+                        # print(file_path, "md5 不同")
+                        file_modified_time = get_modified_time(file_path)
+                        text = "md5 不同 开始下载:{}".format(file_path)
+                        print(text)
+                        download_file(url=value["url"], file_path=file_path)
+                    else:
+                        # print(file_path, "md5 相同")
+                        pass
+                else:
+                    text = "文件不存在 开始下载:{}".format(file_path)
+                    print(text)
+                    time.sleep(1)
+                    download_file(url=value["url"], file_path=file_path)
+
+        else:
+            print("获取更新文件内容失败")
+
+    def get_update_file(self, type="client_camera", plugins_name="plugins_A"):
+        """
+        根据类型和插件名称获取更新文件内容。
+
+        调用外部API查询客户端插件信息,并尝试下载指定名称的插件文件内容。
+
+        参数:
+        - type: 插件类型,默认为"client_camera"。
+        - plugins_name: 插件名称,默认为"plugins_A"。
+
+        返回:
+        - 插件文件内容字符串,如果获取成功。
+        - None,如果获取失败或出现错误。
+        """
+        url = HLM_HOST + "/api/openai/query_client_addons"
+        params = {"type": type}
+        try:
+            response = requests.get(url, params=params, timeout=10)
+            response.raise_for_status()
+            raw_data = response.json()
+
+            # 检查 raw_data 和 raw_data["data"] 是否存在
+            if not raw_data or not raw_data.get("data"):
+                return None
+
+            # 使用 next 函数简化查找逻辑
+            item = next((item for item in raw_data["data"]["list"] if item["name"] == plugins_name), None)
+            if item:
+                url = item["url"]
+                response = requests.get(url, timeout=10)
+                response.raise_for_status()
+                return json.loads(response.text)
+            return None
+        except requests.RequestException as e:
+            print(f"An error occurred: {e}")
+            return None

+ 2 - 0
python/settings.py

@@ -27,3 +27,5 @@ MAX_BYTES = config.get("log", "max_bytes")
 print("Max bytes is", MAX_BYTES)
 # 备份数量
 BACKUP_COUNTS = config.get("log", "backup_counts")
+# 远程服务器地址
+HLM_HOST = config.get("log", "hlm_host")

+ 61 - 0
python/utils/utils_func.py

@@ -0,0 +1,61 @@
+
+import os
+from hashlib import sha256, md5
+from datetime import datetime
+import requests
+
+def get_md5(file_path):
+    data_md5 = None
+    if os.path.isfile(file_path):
+        f = open(file_path, 'rb')
+        md5_obj = md5()
+        md5_obj.update(f.read())
+        hash_code = md5_obj.hexdigest()
+        f.close()
+        data_md5 = str(hash_code).lower()
+    return data_md5
+
+def get_modified_time(file_path):
+    # 获取文件最后修改的时间戳
+    timestamp = os.path.getmtime(file_path)
+    # 将时间戳转换为datetime对象,并格式化为指定格式的字符串
+    modified_time = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
+    return modified_time
+
+def compare_two_times(time_str1, time_str2):
+    # 定义时间格式
+    time_format = "%Y-%m-%d %H:%M:%S"
+    # 将时间字符串解析为datetime对象
+    time1 = datetime.strptime(time_str1, time_format)
+    time2 = datetime.strptime(time_str2, time_format)
+
+    # 比较两个时间
+    if time1 > time2:
+        # print(f"{time_str1} 比 {time_str2} 新。")
+        return "left_new"
+    elif time1 < time2:
+        # print(f"{time_str2} 比 {time_str1} 新。")
+        return "right_new"
+    else:
+        # print("两个时间相等。")
+        return "is_same"
+
+
+def download_file(url, file_path):
+    try:
+        root_path, file_name = os.path.split(file_path)
+        check_path(root_path)
+        response = requests.get(url)
+        _content = response.content
+        with open(file_path, 'wb') as f:
+            f.write(_content)
+        print("下载成功:{}".format(file_path))
+    except:
+        print("下载失败:{}".format(file_path))
+
+def check_path(_path):
+    if not os.path.exists(_path):
+        # 创建多级目录
+        os.makedirs(_path, exist_ok=True)
+        # os.mkdir(_path)
+    return True