代码优化
This commit is contained in:
parent
93e016b8d6
commit
ffc5c5bf90
51
main.py
51
main.py
|
|
@ -8,8 +8,7 @@ from typing import Dict, Any, Optional, List
|
||||||
from fastapi import FastAPI, HTTPException, Depends
|
from fastapi import FastAPI, HTTPException, Depends
|
||||||
|
|
||||||
from public_function.public_func import read_config
|
from public_function.public_func import read_config
|
||||||
from model.model import GoodsInfo, DataReceive
|
from model.model import GoodsInfo, DataReceive, AccountCreate, AccountUpdate, DeviceResetData
|
||||||
from model.model import AccountCreate, AccountUpdate, DeviceResetData
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
@ -22,7 +21,7 @@ def get_config():
|
||||||
from public_function.public_func import read_config
|
from public_function.public_func import read_config
|
||||||
return read_config(config_path)
|
return read_config(config_path)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
logger.warning("未找到read_config函数,使用默认配置")
|
print(f"未找到read_config函数,使用默认配置")
|
||||||
return {'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'password', 'db': 'test_db', 'max_overflow': 10}
|
return {'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'password', 'db': 'test_db', 'max_overflow': 10}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -33,7 +32,7 @@ def get_account_manager():
|
||||||
from account_management.deal_account import DealAccount
|
from account_management.deal_account import DealAccount
|
||||||
return DealAccount(config)
|
return DealAccount(config)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
logger.warning("未找到DealAccount类,返回模拟实例")
|
print(f"未找到DealAccount类,返回模拟实例")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -44,7 +43,18 @@ def get_task_manager():
|
||||||
from task_management.all_task_management import AllTask
|
from task_management.all_task_management import AllTask
|
||||||
return AllTask(config)
|
return AllTask(config)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
logger.warning("未找到AllTask类,返回模拟实例")
|
print(f"未找到AllTask类,返回模拟实例")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_reset_manager():
|
||||||
|
"""设备重置管理器"""
|
||||||
|
config = get_config()
|
||||||
|
try:
|
||||||
|
from task_management.all_task_management import AllTask
|
||||||
|
return AllTask(config)
|
||||||
|
except ImportError:
|
||||||
|
print("未找到 类,返回模拟实例")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -79,7 +89,6 @@ async def add_account(account_data: AccountCreate, account_manager: Any = Depend
|
||||||
- **app_name**: 应用名称
|
- **app_name**: 应用名称
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
print(account_data.model_dump())
|
|
||||||
# 这里应该调用实际的添加账号方法
|
# 这里应该调用实际的添加账号方法
|
||||||
result = await account_manager.add_account([account_data.model_dump()])
|
result = await account_manager.add_account([account_data.model_dump()])
|
||||||
if result:
|
if result:
|
||||||
|
|
@ -125,7 +134,7 @@ async def receive_data(task_data: DataReceive, task_manager: Any = Depends(get_t
|
||||||
return {"code": 200, "message": "数据保存成功", "data": result}
|
return {"code": 200, "message": "数据保存成功", "data": result}
|
||||||
raise HTTPException(status_code=404, detail="抓取商品数据失败,请重新尝试")
|
raise HTTPException(status_code=404, detail="抓取商品数据失败,请重新尝试")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"<UNK>: {e}")
|
print(f"{get_local_time()},商品数据处理失败,失败原因: {e}")
|
||||||
raise HTTPException(status_code=500, detail="获取数据失败;失败原因{}".format(e))
|
raise HTTPException(status_code=500, detail="获取数据失败;失败原因{}".format(e))
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -143,20 +152,20 @@ async def get_goods_info(task_data: GoodsInfo, task_manager: Any = Depends(get_t
|
||||||
raise HTTPException(status_code=500, detail="获取数据失败;失败原因{}".format(e))
|
raise HTTPException(status_code=500, detail="获取数据失败;失败原因{}".format(e))
|
||||||
|
|
||||||
|
|
||||||
# @app.get("/device_reset", summary="设备重置")
|
@app.get("/device_reset", summary="设备重置")
|
||||||
# async def device_reset(task_data: GoodsInfo, reset_manager: Any = Depends(get_reset_manager)):
|
async def device_reset(task_data: DeviceResetData, reset_manager: Any = Depends(get_reset_manager)):
|
||||||
# """设备重置接口"""
|
"""设备重置接口"""
|
||||||
# try:
|
try:
|
||||||
# params = task_data.model_dump()
|
params = task_data.model_dump()
|
||||||
# params['task_id'] = uuid.uuid4().hex
|
params['task_id'] = uuid.uuid4().hex
|
||||||
# # 将任务记录到mysql
|
# 将任务记录到mysql
|
||||||
# # result = await task_manager.task_distribution(params)
|
result = await reset_manager.task_distribution(params)
|
||||||
# # if result:
|
if result:
|
||||||
# # return {"code": 200, "message": "<UNK>", "data": result}
|
return {"code": 200, "message": "<UNK>", "data": result}
|
||||||
# raise HTTPException(status_code=404, detail="抓取商品数据失败,请重新尝试")
|
raise HTTPException(status_code=404, detail="抓取商品数据失败,请重新尝试")
|
||||||
# except Exception as e:
|
except Exception as e:
|
||||||
# print(f"<UNK>: {e}")
|
print(f"设备重置失败,失败原因: {e}")
|
||||||
# raise HTTPException(status_code=500, detail="获取数据失败;失败原因{}".format(e))
|
raise HTTPException(status_code=500, detail="获取数据失败;失败原因{}".format(e))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,28 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
import yaml
|
import yaml
|
||||||
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
from logging.handlers import TimedRotatingFileHandler
|
||||||
|
|
||||||
|
|
||||||
|
def create_logger():
|
||||||
|
now_date = datetime.now().strftime('%Y%m%d')
|
||||||
|
log_filename = os.path.join(Path(__file__).resolve().parent.parent, f'logs/crawler_task_{now_date}.log')
|
||||||
|
path = Path(log_filename).resolve().parent
|
||||||
|
os.makedirs(path, exist_ok=True)
|
||||||
|
|
||||||
|
logger = logging.getLogger("emu_dsl")
|
||||||
|
# 防止重复添加handler
|
||||||
|
if logger.handlers:
|
||||||
|
return logger
|
||||||
|
|
||||||
|
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||||
|
file_handler = TimedRotatingFileHandler(log_filename, when='midnight', backupCount=7, encoding='utf-8')
|
||||||
|
file_handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(file_handler)
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
return logger
|
||||||
|
|
||||||
|
|
||||||
def read_config(path):
|
def read_config(path):
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue