commit 3a100ec41fc8b8975e4b08e38207f37a8c54ba47 Author: unknown <45275340@qq.com> Date: Wed Nov 11 09:43:32 2026 +0800 Initial project import. Add the cartype scripts, incremental runner, scheduler helper, and project notes so the project can be versioned and pushed to the remote repository. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c77ba28 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.pyc +cartype_state.json +cartype_incremental.log diff --git a/cartype.py b/cartype.py new file mode 100644 index 0000000..ba476fc --- /dev/null +++ b/cartype.py @@ -0,0 +1,40 @@ +import json + +import newsetting + +tent = newsetting.All_Setting('192.168.5.2',3306,'project_company_travel') + +def get_cartype(raw_uuid): + + sql1 = f""" + select json_data from rawdata where uuid = '{raw_uuid}' + """ + data = tent.get_shoppingmalls(sql1)[0][0] + # data2 = json.loads(data)['requests'] + json_data = json.loads(json.loads(data)['requests']) + vehicle = json_data['data']['vehicle'] + carType = vehicle['carType'] + color = vehicle['color'] + return carType,color + # input(1) + +def update_data(id,carType,color): + sql = f""" + update order_detail_new set carType = '{carType}',color = '{color}' where id = {id} + """ + tent.update_data(sql) + + +sql1 = """ +select id,raw_uuid from order_detail_new where raw_uuid is not null and amap_order_id is not null and id >= 103396 +""" + + + +a1 = tent.get_shoppingmalls(sql1) +for i in a1: + id, raw_uuid = i + print(i) + carType,color = get_cartype(raw_uuid) + update_data(id,carType,color) + # input(1) diff --git a/cartype_incremental.py b/cartype_incremental.py new file mode 100644 index 0000000..4dd74d9 --- /dev/null +++ b/cartype_incremental.py @@ -0,0 +1,139 @@ +import json +from datetime import datetime +from pathlib import Path + +import newsetting + + +tent = newsetting.All_Setting("192.168.5.2", 3306, "project_company_travel") + +BASELINE_START_ID = 103396 +WRITE_TO_DB = True +CONTINUE_ON_ERROR = False +MAX_ROWS_PER_RUN = None + +BASE_DIR = Path(__file__).resolve().parent +STATE_FILE = BASE_DIR / "cartype_state.json" +LOG_FILE = BASE_DIR / "cartype_incremental.log" + + +def log(message): + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + line = f"[{timestamp}] {message}" + print(line) + with LOG_FILE.open("a", encoding="utf-8") as file: + file.write(line + "\n") + + +def load_state(): + if not STATE_FILE.exists(): + return { + "last_processed_id": BASELINE_START_ID - 1, + "last_run_at": None, + "last_status": "never_run", + } + + with STATE_FILE.open("r", encoding="utf-8") as file: + return json.load(file) + + +def save_state(last_processed_id, status, processed_count, last_error=None): + state = { + "last_processed_id": last_processed_id, + "last_run_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "last_status": status, + "processed_count": processed_count, + "last_error": last_error, + } + with STATE_FILE.open("w", encoding="utf-8") as file: + json.dump(state, file, ensure_ascii=False, indent=2) + + +def escape_sql_text(value): + if value is None: + return "" + return str(value).replace("'", "''") + + +def get_pending_orders(last_processed_id): + limit_sql = "" + if MAX_ROWS_PER_RUN: + limit_sql = f" limit {MAX_ROWS_PER_RUN}" + + sql = f""" + select id, raw_uuid + from order_detail_new + where raw_uuid is not null + and amap_order_id is not null + and id > {last_processed_id} + order by id asc{limit_sql} + """ + return tent.get_shoppingmalls(sql) + + +def get_cartype(raw_uuid): + sql = f""" + select json_data from rawdata where uuid = '{raw_uuid}' + """ + result = tent.get_shoppingmalls(sql) + if not result: + raise ValueError(f"rawdata 未找到 uuid={raw_uuid}") + + data = result[0][0] + request_payload = json.loads(data)["requests"] + json_data = json.loads(request_payload) + vehicle = json_data["data"]["vehicle"] + car_type = vehicle["carType"] + color = vehicle["color"] + return car_type, color + + +def update_data(order_id, car_type, color): + safe_car_type = escape_sql_text(car_type) + safe_color = escape_sql_text(color) + sql = f""" + update order_detail_new + set carType = '{safe_car_type}', color = '{safe_color}' + where id = {order_id} + """ + if WRITE_TO_DB: + tent.update_data(sql) + else: + log(f"仅预览 SQL,未写库: id={order_id}") + + +def main(): + state = load_state() + last_processed_id = state.get("last_processed_id", BASELINE_START_ID - 1) + log(f"开始执行,当前起始 id: {last_processed_id}") + + orders = get_pending_orders(last_processed_id) + if not orders: + log("本次没有待处理数据。") + save_state(last_processed_id, "no_data", 0) + return + + processed_count = 0 + current_last_id = last_processed_id + + for order_id, raw_uuid in orders: + try: + car_type, color = get_cartype(raw_uuid) + update_data(order_id, car_type, color) + current_last_id = order_id + processed_count += 1 + log(f"处理成功: id={order_id}, carType={car_type}, color={color}") + save_state(current_last_id, "running", processed_count) + except Exception as exc: + error_message = f"id={order_id}, raw_uuid={raw_uuid}, error={exc}" + log(f"处理失败: {error_message}") + save_state(current_last_id, "failed", processed_count, error_message) + if not CONTINUE_ON_ERROR: + raise + + save_state(current_last_id, "success", processed_count) + log(f"执行完成,本次共处理 {processed_count} 条,最后 id={current_last_id}") + + +if __name__ == "__main__": + main() diff --git a/cartype_incremental_README.md b/cartype_incremental_README.md new file mode 100644 index 0000000..ab73938 --- /dev/null +++ b/cartype_incremental_README.md @@ -0,0 +1,84 @@ +# cartype 增量执行方案 + +## 目标 + +不修改原始 `cartype.py`,新建一个独立脚本,实现以下能力: + +1. 每次运行只处理上次执行后新增的数据 +2. 把本次成功处理到的最后一个 `id` 记录到本地状态文件 +3. 下次运行时,SQL 自动从这个 `id` 继续往后处理 +4. 配合 Windows 计划任务,在每天 `08:00` 到次日 `00:00` 每小时执行一次 + +## 新文件说明 + +- `cartype_incremental.py` + - 增量处理主脚本 +- `cartype_state.json` + - 运行后自动生成的状态文件 +- `cartype_incremental.log` + - 运行日志文件 +- `register_cartype_hourly_task.ps1` + - Windows 定时任务注册脚本 + +## 关键实现 + +### 1. 起始 id 逻辑 + +首次运行时使用: + +```sql +id > 103395 +``` + +也就是等价于你原脚本中的: + +```sql +id >= 103396 +``` + +后续运行时,读取 `cartype_state.json` 中的 `last_processed_id`,然后执行: + +```sql +id > last_processed_id +``` + +### 2. 为什么记录“最后成功 id” + +脚本是逐条处理的,每成功一条就更新状态文件。 + +这样即使中途报错,状态文件里仍然保存的是“最后成功处理到的 id”,下次重新跑时会从失败那条继续,不会跳过异常数据。 + +### 3. 定时任务时间范围 + +`register_cartype_hourly_task.ps1` 会注册一个 Windows 计划任务: + +- 每天开始时间:`08:00` +- 重复间隔:`1 小时` +- 持续时长:`17 小时` + +对应实际触发时间为: + +- `08:00` +- `09:00` +- `10:00` +- ... +- `23:00` +- `00:00` + +## 可调开关 + +`cartype_incremental.py` 里预留了几个常用开关: + +- `WRITE_TO_DB = True` + - 是否真的写数据库 +- `CONTINUE_ON_ERROR = False` + - 遇到异常时是否继续跑后续数据 +- `MAX_ROWS_PER_RUN = None` + - 单次最多处理多少条,`None` 表示不限制 + +## 建议执行顺序 + +1. 先手动运行一次 `cartype_incremental.py` +2. 确认生成了 `cartype_state.json` 和日志 +3. 确认数据库更新符合预期 +4. 再执行 `register_cartype_hourly_task.ps1` 注册定时任务 diff --git a/da b/da new file mode 100644 index 0000000..2d940de --- /dev/null +++ b/da @@ -0,0 +1 @@ +{"code":1,"data":{"amapRideType":"gd_express","beforeTripPrepayAmount":2049,"carListTraceId":"a00043a68988ccbf4c30a1b91dcc4985b120","carouselOrder":0,"carpoolTripsInfo":{},"channel":"etravel_caocao","commonInfo":{"tip":"接单贴士"},"cpData":{"amapRideType":"gd_express","brandIconUrl":"https://aos-cdn-files.cn-hangzhou.oss.aliyun-inc.com/aos-amaps/private_car/823fc705b8e511e9b114186590d5b589_new_etravel_caocao.png","brandName":"曹操出行","brandRideType":"曹操-经济型","businessModel":1,"cpCode":"9005","cpOid":"6013200961625110","cpSource":"etravel_caocao_api","isYueyue":false,"numberOfSeats":"5座","productType":"express-car","rideType":"new_energy","rideTypeName":"曹操出行","serviceTel":"4006081111","spSupport":false},"cpStatus":"Accepted","createTime":1784347709969,"customerService":"4008802252","dataComplete":true,"departTime":1784347710000,"driver":{"appUid":"1224736183","brandIcon":"https://aos-cdn-files.cn-hangzhou.oss.aliyun-inc.com/aos-amaps/private_car/823fc705b8e511e9b114186590d5b589_new_etravel_caocao.png","driverId":"5446849538","driverPageUrl":"https://dache.amap.com/common/amap#/driver/home?driverUniqueId=&amapOrderId=40814840007720077592959467","driverTag":"https://sharetrip-resource.amap.com/cc183c49-4-192-48.png?notheme=1","driverTagPics":["https://sharetrip-resource.amap.com/cc183c49-4-192-48.png?notheme=1"],"finishOrderCntSp":1566,"imSwitch":29,"name":"王师傅","phoneNumber":"+8618613023949","pictureUrl":"","privacyNumber":"+8613143756944","rating":4.5,"supportIm":true},"endInfo":{"endAdcode":"440103","endLat":"23.125643","endLon":"113.240671","endName":"华润万家","endPOI":"B00140U6H5","originalEndLat":"23.125968","originalEndLon":"113.240151"},"etravelOrderId":"6013200961625110","flashMultiCpList":[],"gdServiceId":1,"gmtModified":1784347718799,"highQualityFlag":false,"matrixContentInfo":{"accessId":"213d901517843477194403362e0cf9","lubanData":{"CODVehiclePicture":{"dataList":[{"biz":{"__contentId__":"matrix|config_16840","carIconSrc":"https://img.alicdn.com/imgextra/i1/O1CN01tehe6Q1NbM13hb9Zw_!!6000000001588-2-tps-60-120.png","imgSrc":"https://img.alicdn.com/imgextra/i1/O1CN01qAh78b21NgnZQkoyT_!!6000000006973-2-tps-430-172.png"},"protocol":{"contentId":"config_16840","contentName":"订单详情-车辆图片-<默认>-白,白色,冰晶白-gd_express-<默认>"},"uiSchemaId":"934"}]}},"orderStatus":"103"},"maxWaitTime":"","miniProgramType":5,"multiCP":[{"cpInfo":{"amapRideType":"gd_express","brandIconUrl":"https://aos-cdn-files.cn-hangzhou.oss.aliyun-inc.com/aos-amaps/private_car/823fc705b8e511e9b114186590d5b589_new_etravel_caocao.png","brandName":"曹操出行","brandRideName":"曹操-经济型","businessModel":1,"cpAmapOid":"40814840008323182011149819","cpAmapOrderId":"40814840008323182011149819","cpCode":9005,"cpOrderId":"6013200961625110","cpSource":"etravel_caocao_api","productType":"express-car","rideType":"new_energy","rideTypeName":"曹操出行","serviceTel":"4006081111","spSupport":false},"preTravel":{"city":"020","cpOriginDelay":0,"driverArriveTime":180,"estimateMileage":6917,"estimatePrice":1847,"estimateTime":1148,"infoFeesFree":false},"waitInfo":{}}],"orderTag":{"boundCpType":1,"interlinkOrder":1,"interlinkOrderFinish":0,"isMultiDayOrder":false,"newUserFlag":0,"prePay":0,"priceType":0,"priceTypeDetail":0},"passengerInfo":{"allowChange":true,"appUid":"1000000002995814840","passengerNickName":"乘客8481","passengerPhone":"13288488481","validityTime":30},"pickupSpotId":"","pollConfig":{"partStatus":0,"pollInterval":30000},"queueOrder":0,"quickDriver":{"quickSelected":0},"reassignOrder":0,"showCurrency":"CNY","showStatus":5,"startInfo":{"pickupSpotId":"","startAdcode":"440104","startLat":"23.129190","startLon":"113.299020","startName":"东山宾馆(南二门)","startPOI":"B00140654A","startTimezone":"UTC+08:00"},"status":103,"subGdServiceId":0,"subMiniProgramType":0,"toast":"","vehicle":{"carType":"吉利曹操60","color":"白色","licensePlate":"粤AB44166","pictureUrl":"https://img.alicdn.com/imgextra/i1/O1CN01qAh78b21NgnZQkoyT_!!6000000006973-2-tps-430-172.png"}},"dataComplete":true,"etag":"40814840007720077592959467-103_19f7369748f","message":"Successful","result":true,"timestamp":1784347719459,"version":"1.0"} diff --git a/newsetting.py b/newsetting.py new file mode 100644 index 0000000..3beed32 --- /dev/null +++ b/newsetting.py @@ -0,0 +1,161 @@ +import re +import pymysql + +class All_Setting(): + def __init__(self,host,port,db): + self.host = host + self.port = port + self.db = db + + def remove_symbols(self,text): + pattern = re.compile(r'[^\w\s]') + return pattern.sub('', text) + + def get_chinese(self,text,printTxt=False): + # text = "海王星辰(广州智慧城店)" + pattern = r'[^\w\s]' + result = re.sub(pattern, '', text) + if printTxt: + print(result) + return result + + def get_shoppingmalls(self,sql): + res_list = [] + conn = pymysql.connect( + host= self.host, # 我的IP地址 + port=self.port, # 不是字符串不需要加引号。 + user='root', + password='Aliyun@7646!', + db=self.db, + charset='utf8mb4' + ) + if conn: + print('ok') + cursor = conn.cursor() + res = cursor.execute(sql) + c2 = cursor.fetchall() + return c2 + + def write_data(self,sql,data): + conn = pymysql.connect( + host= self.host, # 我的IP地址 + port=self.port, # 不是字符串不需要加引号。 + user='root', + password='Aliyun@7646!', + db=self.db, + charset='utf8mb4' + ) + # 拿到游标 + if conn: + print("连接成功!") + cursor = conn.cursor() + cursor.executemany(sql,data) + conn.commit() + cursor.close() + + + def update_data(self,sql): + conn = pymysql.connect( + host= self.host, # 我的IP地址 + port=self.port, # 不是字符串不需要加引号。 + user='root', + password='Aliyun@7646!', + db=self.db, + charset='utf8mb4' + ) + # 拿到游标 + if conn: + print("连接成功!") + cursor = conn.cursor() + cursor.execute(sql) + conn.commit() + cursor.close() + + def write_data_one(self,sql,data): + conn = pymysql.connect( + host= self.host, # 我的IP地址 + port=self.port, # 不是字符串不需要加引号。 + user='root', + password='Aliyun@7646!', + db=self.db, + charset='utf8mb4' + ) + # 拿到游标 + if conn: + print("连接成功!") + cursor = conn.cursor() + cursor.execute(sql,data) + conn.commit() + cursor.close() + +import json +# import time,requests + + +def get_sign_meituan(url, dfpid, data): + url_mtg = "http://118.89.119.254:18003/mt_jym_1_2" + payload = json.dumps({ + "url": url, + "data": data, + "dfpid": dfpid, + "method": "POST", + "ua_type": "android" + }) + headers = { + 'token': 'j760kynsopjfm0sa9ghjwsd', + 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)', + 'Content-Type': 'application/json' + } + response1 = requests.request("POST", url_mtg, headers=headers, data=payload) + print(response1.text) + mtgsig1 = response1.json() + return str(mtgsig1) + +def get_sign_waimai(url, dfpid, data): + print('我是外卖mtg') + + url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym" + payload = json.dumps({ + "url": url, + "data": data, + "dfpid": dfpid, + "method": "POST", + # "ua_type": "android" + }) + headers = { + 'token': 'j760kynsopjfm0sa9ghjwsd', + 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)', + 'Content-Type': 'application/json' + } + response = requests.request("POST", url_mtg, headers=headers, data=payload) + mtgsig = response.json() + print(mtgsig) + return str(mtgsig) + +def get_Datatext(dataq): + str1 = '' + for i in dataq: + key, value = i, dataq[i] + str2 = f'{key}={value}&' + str1 = str1 + str2 + data = str1[0:-1] + return data + + +tent = All_Setting(host='8.138.160.45',port=3306,db='program_user_list') +tent2 = All_Setting(host='183.6.7.91',port=33016,db='elm_meishi') +# tent3 = All_Setting(host='42.192.49.62',port=3306,db='MT_shop3') + + +# sql1 = """SELECT distinct prox FROM `MT_shop2`.`category_table` WHERE `created_at` > '2025-3-24' LIMIT 0,1000""" +# prox = tent2.get_shoppingmalls(sql1)[0][0] +# print(prox) +# print(json.loads(prox)) +# prox2 = json.dumps(prox) +# print(prox2) +# sql2 = """SELECT distinct `index` FROM `MT_shop2`.`category_table` WHERE `created_at` > '2025-3-24' LIMIT 0,1000""" +# lis = tent2.get_shoppingmalls(sql2) +# for i in lis: +# indexs = (i[0]) +# sql4 = f"""update `MT_shop2`.`category_table` set prox = {prox2} WHERE `created_at` > '2025-3-24' """ +# tent2.update_data(sql4) \ No newline at end of file diff --git a/register_cartype_hourly_task.ps1 b/register_cartype_hourly_task.ps1 new file mode 100644 index 0000000..5632038 --- /dev/null +++ b/register_cartype_hourly_task.ps1 @@ -0,0 +1,27 @@ +$pythonExe = "C:\pyui软件项目\.venv\Scripts\python.exe" +$scriptPath = "C:\Users\jimmy\Desktop\高德企业版\添加carType字段\cartype_incremental.py" +$taskName = "CartypeIncrementalHourly" + +if (!(Test-Path $pythonExe)) { + throw "未找到 Python: $pythonExe" +} + +if (!(Test-Path $scriptPath)) { + throw "未找到脚本: $scriptPath" +} + +$action = New-ScheduledTaskAction -Execute $pythonExe -Argument "`"$scriptPath`"" +$trigger = New-ScheduledTaskTrigger -Daily -At 8:00AM +$trigger.RepetitionInterval = "PT1H" +$trigger.RepetitionDuration = "PT17H" +$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable + +Register-ScheduledTask ` + -TaskName $taskName ` + -Action $action ` + -Trigger $trigger ` + -Settings $settings ` + -Description "每天 08:00 到次日 00:00 每小时执行一次 cartype 增量处理脚本" ` + -Force + +Write-Host "定时任务已注册: $taskName"