代码优化

This commit is contained in:
liujianjiang 2025-12-03 10:20:07 +08:00
parent 862e1f56dd
commit 445e208d82
4 changed files with 22 additions and 16 deletions

View File

@ -29,17 +29,18 @@ class DealAccount:
async def query_account_info(self, params: Dict[str, Any]):
"""查询具体账户信息"""
sql_str = f"""select * from crawler_account_record_info where account_id='{params['account_id']}'"""
sql_str = f"""select account_id,password,app_name,status from crawler_account_record_info
where app_name='{params['app_name']}' and account_id='{params['account_id']}'"""
await self.db_pool.initialize()
result = await self.db_pool.fetch_all(sql_str, )
if result:
return result
return result[0]
return []
async def obtain_account_info(self, app_name, country, number=1):
"""获取指定个数账户信息"""
sql_str = f"""select account_id,password from crawler_account_record_info
where status=1 and app_name='{app_name}' and country='{country}' limit {number}"""
sql_str = f"""select account_id,password,app_name from crawler_account_record_info
where status=1 and app_name='{app_name}' and region='{country}' limit {number}"""
await self.db_pool.initialize()
result = await self.db_pool.fetch_all(sql_str, )
if result:

26
main.py
View File

@ -62,7 +62,7 @@ def get_reset_manager():
# 账号处理相关
@app.get("/obtain_account", summary="获取可用账号")
async def obtain_account(app_name: str, country: str, pad_code: str, account_manager: Any = Depends(get_account_manager)):
async def obtain_account(app_name: str, region: str, account_manager: Any = Depends(get_account_manager)):
"""
获取指定应用的可用账号
- **app_name**: 应用名称
@ -70,12 +70,17 @@ async def obtain_account(app_name: str, country: str, pad_code: str, account_man
"""
if not app_name or not app_name.strip():
raise HTTPException(status_code=400, detail="应用名称不能为空")
if not country or not country.strip():
if not region or not region.strip():
raise HTTPException(status_code=400, detail="国家不能为空会")
try:
result = await account_manager.obtain_account_info(app_name, country)
result = await account_manager.obtain_account_info(app_name, region)
if result:
# 将账号和设备进行记录
set_param = {"status": 2}
print(result)
params = (result[0]["account_id"], result[0]["app_name"])
where_conditions = "account_id = %s and app_name = %s "
await account_manager.update_account_info(set_param=set_param, where_conditions=where_conditions, params=params)
return {"code": 200, "message": "获取账号成功", "data": result[0]}
else:
raise HTTPException(status_code=404, detail="没有可用的账号")
@ -84,8 +89,8 @@ async def obtain_account(app_name: str, country: str, pad_code: str, account_man
raise HTTPException(status_code=404, detail="{}".format(e))
@app.post("/add_account", summary="新增账号")
async def add_account(account_data: AccountCreate, account_manager: Any = Depends(get_account_manager)):
@app.post("/account_status", summary="获取账号状态")
async def account_status(account_data: AccountCreate, account_manager: Any = Depends(get_account_manager)):
"""
新增爬虫账号
- **account_id**: 账号ID
@ -93,13 +98,13 @@ async def add_account(account_data: AccountCreate, account_manager: Any = Depend
- **app_name**: 应用名称
"""
try:
result = await account_manager.add_account([account_data.model_dump()])
result = await account_manager.query_account_info(account_data.model_dump())
if result:
return {"code": 200, "message": "新增账号成功", "data": result}
raise HTTPException(status_code=404, detail="新增账号失败")
return {"code": 200, "message": "获取账号状态", "data": result}
raise HTTPException(status_code=404, detail="获取账号状态")
except Exception as e:
print(f"新增账号失败: {e}")
raise HTTPException(status_code=500, detail="新增账号失败,失败原因:{}".format(e))
print(f"获取账号状态: {e}")
raise HTTPException(status_code=500, detail="获取账号状态,失败原因:{}".format(e))
@app.post("/update_account", summary="账号状态修改")
@ -170,6 +175,7 @@ async def get_goods_info(task_data: GoodsInfo, task_manager: Any = Depends(get_t
params["app_name"] = "Shopee"
params['region'] = params["host"]
params["token"] = token
print(params)
await task_manager.insert_task_record(params)
print(f"开始处理任务: {task_id}")
result = await task_manager.deal_shopee_task(params)

View File

@ -6,8 +6,6 @@ from typing import Optional, Dict, Any
# 定义数据模型
class AccountCreate(BaseModel):
account_id: str = Field(..., description="账号ID")
password: str = Field(..., description="密码")
region: str = Field(..., description="账号所在地区")
app_name: str = Field(..., description="应用名称")

View File

@ -42,6 +42,7 @@ class AllTask:
处理Shopee任务的异步方法
"""
key = f"{param['app_name'].lower()}:{param['region'].lower()}:{param['shop_id']}:{param['item_id']}"
print(key)
result = self.redis_conn.read_data(key)
if result is not None:
print(f"{key} 从Redis缓存中获取到数据")