This commit is contained in:
upload
2026-10-08 17:34:02 +08:00
commit f216f6120b
961 changed files with 25144 additions and 0 deletions
Binary file not shown.
+146
View File
@@ -0,0 +1,146 @@
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
# 名称医乐邦
# 请输入坐标34.268453,117.165798
+230
View File
@@ -0,0 +1,230 @@
import multiprocessing
import json
import newsetting
import time
# 数据库配置
DB_HOST = '192.168.5.2'
DB_PORT = 3307
DB_NAME = 'pyui_all_market'
# workid = '20260409'
# workid = '20260409_test3'
workid = 'upc_all_20260804'
# 进程私有变量
process_tent = None
poi_filter_config = {} # 只存配置表中的店铺
def init_worker():
global process_tent, poi_filter_config
process_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
poi_filter_config = load_poi_filters()
def load_poi_filters():
"""加载配置表中的店铺筛选配置"""
temp_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
# 读取配置表(workid=20260302)
sql = f"""
SELECT poi_id_str, shop_name, tag1, tag1_name, tag2, tag2_name
FROM poi_category_filter
WHERE workid = '{workid}'
"""
result = temp_tent.get_shoppingmalls(sql)
# 建立 shop_name -> 分类配置
filters_by_name = {}
for row in result:
poi_id, shop_name, tag1, tag1_name, tag2, tag2_name = row
shop_key = shop_name.strip() if shop_name else ''
if shop_key not in filters_by_name:
filters_by_name[shop_key] = []
filters_by_name[shop_key].append({
'tag1': tag1,
'tag1_name': tag1_name.strip() if tag1_name else None,
'tag2': tag2,
'tag2_name': tag2_name.strip() if tag2_name else None
})
print(f"配置表中共有 {len(filters_by_name)} 个不同店名")
# 匹配当前workid中的poi_id_str
filters = {}
if filters_by_name:
shop_names = "','".join([k.replace("'", "''") for k in filters_by_name.keys()])
poi_sql = f"""
SELECT DISTINCT poi_id_str, shop_name
FROM food_table
WHERE workid = '{workid}' AND shop_name IN ('{shop_names}')
"""
poi_result = temp_tent.get_shoppingmalls(poi_sql)
for poi_id, shop_name in poi_result:
shop_key = shop_name.strip() if shop_name else ''
if shop_key in filters_by_name:
filters[poi_id] = {
'shop_name': shop_name,
'categories': filters_by_name[shop_key]
}
print(f"已匹配到 {len(filters)} 个门店需要筛选")
return filters
def match_category(cat_tag1_name, cat_tag2_name, config):
"""按分类名字匹配,'全部'或None表示不限制"""
cfg_tag1_name = config.get('tag1_name')
cfg_tag2_name = config.get('tag2_name')
match_tag1 = (cfg_tag1_name is None) or (cfg_tag1_name == '全部') or \
(cat_tag1_name and cat_tag1_name.strip() == cfg_tag1_name)
match_tag2 = (cfg_tag2_name is None) or (cfg_tag2_name == '全部') or \
(cat_tag2_name and cat_tag2_name.strip() == cfg_tag2_name)
return match_tag1 and match_tag2
def get_data_batch(poi_ids):
"""批量获取数据"""
poi_str = "','".join(poi_ids)
cat_sql = f"""
SELECT t1.parent_id,t1.workid,t1.business_code,t1.mt_org_id,t1.poi_id_str,t1.shop_name,t1.address,t1.shipping_fee_tip,t1.min_price_tip,t1.packet_fee_tip,t1.shipping_time,t2.tag1,t2.tag1_name,t2.tag2,t2.tag2_name,t2.tag_type,t2.product_count,t2.allSortedSpuId
from (SELECT * FROM food_table WHERE workid like '%{workid}%' and poi_id_str IN ('{poi_str}')) AS t1
INNER JOIN (SELECT * FROM categorylist2 WHERE batch like '%{workid}%' AND is_ok = 1 and poi_id_str IN ('{poi_str}')) as t2
ON t1.mt_org_id = t2.mt_org_id and t1.poi_id_str = t2.poi_id_str
"""
categories = process_tent.get_shoppingmalls(cat_sql)
prod_sql = f"""
SELECT poi_id_str, product_id,product_name,description,praise_content,month_saled_content,skus_id,spec,actual_price,price,origin_price,activity_price,min_order_count,quota_per_order,dynamic_text,dynamic_url,upccode,want_to_buy_content,praise_rate,picture,promotion_info,tag,activity_tag_id,stock_label,real_stock,skus_count,product_label,vague_picture,create_time
FROM `productslist`
where workid like '%{workid}%' and poi_id_str IN ('{poi_str}')
"""
products = process_tent.get_shoppingmalls(prod_sql)
# 筛选分类:配置表有的按黑名单剔除,没有的不筛(保留全部)
filtered_categories = []
for cat in categories:
poi_id = cat[4]
cat_tag1_name = cat[12] if cat[12] else None
cat_tag2_name = cat[14] if cat[14] else None
if poi_id not in poi_filter_config:
filtered_categories.append(cat)
continue
category_configs = poi_filter_config[poi_id]['categories']
excluded = False
for cfg in category_configs:
if match_category(cat_tag1_name, cat_tag2_name, cfg):
excluded = True
break
if not excluded:
filtered_categories.append(cat)
return filtered_categories, products
def process_batch_task(poi_ids):
"""处理一批门店的数据"""
try:
categories, products = get_data_batch(poi_ids)
if not categories or not products:
return poi_ids, []
# 建立商品索引
product_index = {}
for p in products:
poi_id = p[0]
prod_data = p[1:]
if poi_id not in product_index:
product_index[poi_id] = {}
product_index[poi_id][str(prod_data[0])] = prod_data
local_results = []
for cat in categories:
poi_id = cat[4]
if poi_id not in product_index:
continue
try:
all_spu_json = cat[-1]
spu_ids = json.loads(all_spu_json)
for spu_id in spu_ids:
spu_id_str = str(spu_id)
if spu_id_str in product_index[poi_id]:
prod = product_index[poi_id][spu_id_str]
local_results.append(cat + prod)
except:
continue
print(f'[{time.strftime("%H:%M:%S")}] 批次完成: {len(poi_ids)} 门店, 匹配: {len(local_results)} 条')
return poi_ids, local_results
except Exception as e:
print(f"批次处理出错: {e}")
import traceback
traceback.print_exc()
return poi_ids, []
def main():
global poi_filter_config
# 1. 加载筛选配置(只包含有配置的店铺)
poi_filter_config = load_poi_filters()
# 2. 获取所有门店(原逻辑)
temp_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
task = temp_tent.get_shoppingmalls(f"SELECT DISTINCT poi_id_str FROM food_table WHERE workid like '%{workid}%'")
all_poi_ids = [i[0] for i in task]
print(
f"总共有 {len(all_poi_ids)} 个门店,其中 {len(poi_filter_config)} 个需要筛选,{len(all_poi_ids) - len(poi_filter_config)} 个按原逻辑处理")
# 3. 分组处理所有门店
batch_size = 20
poi_batches = [all_poi_ids[i:i + batch_size] for i in range(0, len(all_poi_ids), batch_size)]
print(f"共分成 {len(poi_batches)} 个批次")
# 4. 准备写入
final_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
insert_sql = """
insert into ready_list2_copy1 (parent_id,workid,business_code,mt_org_id, poi_id_str, shop_name, address, shipping_fee_tip, min_price_tip, packet_fee_tip, shipping_time, tag1, tag1_name, tag2, tag2_name, tag_type, product_count, allSortedSpuId,product_id, product_name, description, praise_content, month_saled_content, skus_id,spec, actual_price, price, origin_price, activity_price, min_order_count, quota_per_order, dynamic_text, dynamic_url, upccode, want_to_buy_content, praise_rate, picture, promotion_info, tag, activity_tag_id, stock_label, real_stock, skus_count, product_label, vague_picture,create_time) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
"""
# 5. 启动进程池
num_processes = 32
total_written = 0
with multiprocessing.Pool(processes=num_processes, initializer=init_worker) as pool:
for handled_ids, res_list in pool.imap_unordered(process_batch_task, poi_batches):
try:
ids_str = "','".join(handled_ids)
update_sql = f"UPDATE food_table SET is_ok = 1 WHERE workid like '%{workid}%' AND poi_id_str IN ('{ids_str}')"
final_tent.update_data(update_sql)
except Exception as e:
print(f"更新状态失败: {e}")
if res_list:
try:
final_tent.write_data(insert_sql, res_list)
total_written += len(res_list)
print(f'>>> 已写入数据库: {len(res_list)} 条 (累计: {total_written} 条)')
del res_list
except Exception as e:
print(f"写入数据库失败: {e}")
print(f"[{time.strftime('%H:%M:%S')}] 完成,共计 {total_written} 条数据。")
# temp_tent.update_data(f"UPDATE ready_list2_copy1 SET business_code ='SURPERMARKET' WHERE business_code = 'SURPERMARKET1' and workid ='{workid}'")
# print('月报更新')
# 110809
if __name__ == '__main__':
main()
+227
View File
@@ -0,0 +1,227 @@
import multiprocessing
import json
import newsetting
import time
# 数据库配置
DB_HOST = '192.168.5.2'
DB_PORT = 3307
DB_NAME = 'pyui_all_market'
# workid = '20260409'
# workid = '20260409_test3'
workid = 'upc_all_20260804'
# 分类表配置:pyui_all_market 用 categorylist2 + batch
CATEGORY_TABLE = 'categorylist2'
CATEGORY_ID_FIELD = 'batch'
# 进程私有变量
process_tent = None
mt_org_filter_config = {} # 只存配置表中的店铺
def init_worker():
global process_tent, mt_org_filter_config
process_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
mt_org_filter_config = load_mt_org_filters()
def load_mt_org_filters():
"""加载配置表中的店铺筛选配置,按 mt_org_id 建立索引"""
temp_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
sql = f"""
SELECT poi_id_str, shop_name, tag1, tag1_name, tag2, tag2_name
FROM poi_category_filter
WHERE workid = '{workid}'
"""
result = temp_tent.get_shoppingmalls(sql)
filters_by_name = {}
for row in result:
poi_id, shop_name, tag1, tag1_name, tag2, tag2_name = row
shop_key = shop_name.strip() if shop_name else ''
if shop_key not in filters_by_name:
filters_by_name[shop_key] = []
filters_by_name[shop_key].append({
'tag1': tag1,
'tag1_name': tag1_name.strip() if tag1_name else None,
'tag2': tag2,
'tag2_name': tag2_name.strip() if tag2_name else None
})
print(f"配置表中共有 {len(filters_by_name)} 个不同店名")
filters = {}
if filters_by_name:
shop_names = "','".join([k.replace("'", "''") for k in filters_by_name.keys()])
org_sql = f"""
SELECT DISTINCT mt_org_id, shop_name
FROM food_table
WHERE workid = '{workid}' AND shop_name IN ('{shop_names}')
"""
org_result = temp_tent.get_shoppingmalls(org_sql)
for mt_org_id, shop_name in org_result:
shop_key = shop_name.strip() if shop_name else ''
if shop_key in filters_by_name:
filters[mt_org_id] = {
'shop_name': shop_name,
'categories': filters_by_name[shop_key]
}
print(f"已匹配到 {len(filters)} 个门店需要筛选")
return filters
def match_category(cat_tag1_name, cat_tag2_name, config):
"""按分类名字匹配,'全部'或None表示不限制"""
cfg_tag1_name = config.get('tag1_name')
cfg_tag2_name = config.get('tag2_name')
match_tag1 = (cfg_tag1_name is None) or (cfg_tag1_name == '全部') or \
(cat_tag1_name and cat_tag1_name.strip() == cfg_tag1_name)
match_tag2 = (cfg_tag2_name is None) or (cfg_tag2_name == '全部') or \
(cat_tag2_name and cat_tag2_name.strip() == cfg_tag2_name)
return match_tag1 and match_tag2
def get_data_batch(mt_org_ids):
ids_str = "','".join(mt_org_ids)
cat_sql = f"""
SELECT t1.parent_id,t1.workid,t1.business_code,t1.mt_org_id,t1.poi_id_str,t1.shop_name,t1.address,t1.shipping_fee_tip,t1.min_price_tip,t1.packet_fee_tip,t1.shipping_time,t2.tag1,t2.tag1_name,t2.tag2,t2.tag2_name,t2.tag_type,t2.product_count,t2.allSortedSpuId
from (SELECT * FROM food_table WHERE workid = '{workid}' and mt_org_id IN ('{ids_str}')) AS t1
INNER JOIN (SELECT * FROM {CATEGORY_TABLE} WHERE {CATEGORY_ID_FIELD} = '{workid}' AND is_ok = 1 and mt_org_id IN ('{ids_str}')) as t2
ON t1.mt_org_id = t2.mt_org_id
"""
categories = process_tent.get_shoppingmalls(cat_sql)
prod_sql = f"""
SELECT mt_org_id, product_id,product_name,description,praise_content,month_saled_content,skus_id,spec,actual_price,price,origin_price,activity_price,min_order_count,quota_per_order,dynamic_text,dynamic_url,upccode,want_to_buy_content,praise_rate,picture,promotion_info,tag,activity_tag_id,stock_label,real_stock,skus_count,product_label,vague_picture,create_time
FROM productslist
where workid = '{workid}' and mt_org_id IN ('{ids_str}')
"""
products = process_tent.get_shoppingmalls(prod_sql)
filtered_categories = []
for cat in categories:
mt_org_id = cat[3]
cat_tag1_name = cat[12] if cat[12] else None
cat_tag2_name = cat[14] if cat[14] else None
if mt_org_id not in mt_org_filter_config:
filtered_categories.append(cat)
continue
category_configs = mt_org_filter_config[mt_org_id]['categories']
excluded = False
for cfg in category_configs:
if match_category(cat_tag1_name, cat_tag2_name, cfg):
excluded = True
break
if not excluded:
filtered_categories.append(cat)
return filtered_categories, products
def process_batch_task(mt_org_ids):
try:
categories, products = get_data_batch(mt_org_ids)
if not categories or not products:
return mt_org_ids, []
product_index = {}
for p in products:
mt_org_id = p[0]
prod_data = p[1:]
if mt_org_id not in product_index:
product_index[mt_org_id] = {}
product_index[mt_org_id][str(prod_data[0])] = prod_data
local_results = []
for cat in categories:
mt_org_id = cat[3]
if mt_org_id not in product_index:
continue
try:
all_spu_json = cat[-1]
spu_ids = json.loads(all_spu_json)
for spu_id in spu_ids:
spu_id_str = str(spu_id)
if spu_id_str in product_index[mt_org_id]:
prod = product_index[mt_org_id][spu_id_str]
local_results.append(cat + prod)
except:
continue
print(f'[{time.strftime("%H:%M:%S")}] 批次完成: {len(mt_org_ids)} 门店, 匹配: {len(local_results)} 条')
return mt_org_ids, local_results
except Exception as e:
print(f"批次处理出错: {e}")
import traceback
traceback.print_exc()
return mt_org_ids, []
def main():
global mt_org_filter_config
mt_org_filter_config = load_mt_org_filters()
temp_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
task = temp_tent.get_shoppingmalls(
f"SELECT DISTINCT mt_org_id FROM food_table WHERE workid = '{workid}' AND mt_org_id IS NOT NULL AND mt_org_id != ''"
)
all_mt_org_ids = [i[0] for i in task]
if not all_mt_org_ids:
print('未找到有效 mt_org_id,请检查 food_table 数据')
return
print(
f"总共有 {len(all_mt_org_ids)} 个门店,其中 {len(mt_org_filter_config)} 个需要筛选,"
f"{len(all_mt_org_ids) - len(mt_org_filter_config)} 个按原逻辑处理"
)
batch_size = 20
org_batches = [all_mt_org_ids[i:i + batch_size] for i in range(0, len(all_mt_org_ids), batch_size)]
print(f"共分成 {len(org_batches)} 个批次")
final_tent = newsetting.All_Setting(DB_HOST, DB_PORT, DB_NAME)
insert_sql = """
insert into ready_list2_copy1 (parent_id,workid,business_code,mt_org_id, poi_id_str, shop_name, address, shipping_fee_tip, min_price_tip, packet_fee_tip, shipping_time, tag1, tag1_name, tag2, tag2_name, tag_type, product_count, allSortedSpuId,product_id, product_name, description, praise_content, month_saled_content, skus_id,spec, actual_price, price, origin_price, activity_price, min_order_count, quota_per_order, dynamic_text, dynamic_url, upccode, want_to_buy_content, praise_rate, picture, promotion_info, tag, activity_tag_id, stock_label, real_stock, skus_count, product_label, vague_picture,create_time) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
"""
num_processes = 32
total_written = 0
with multiprocessing.Pool(processes=num_processes, initializer=init_worker) as pool:
for handled_ids, res_list in pool.imap_unordered(process_batch_task, org_batches):
try:
ids_str = "','".join(handled_ids)
update_sql = f"UPDATE food_table SET is_ok = 1 WHERE workid = '{workid}' AND mt_org_id IN ('{ids_str}')"
final_tent.update_data(update_sql)
except Exception as e:
print(f"更新状态失败: {e}")
if res_list:
try:
final_tent.write_data(insert_sql, res_list)
total_written += len(res_list)
print(f'>>> 已写入数据库: {len(res_list)} 条 (累计: {total_written} 条)')
del res_list
except Exception as e:
print(f"写入数据库失败: {e}")
print(f"[{time.strftime('%H:%M:%S')}] 完成,共计 {total_written} 条数据。")
# temp_tent.update_data(f"UPDATE ready_list2_copy1 SET business_code ='SURPERMARKET' WHERE business_code = 'SURPERMARKET1' and workid ='{workid}'")
# print('月报更新')
if __name__ == '__main__':
main()
+123
View File
@@ -0,0 +1,123 @@
import os.path
import re
import pandas
import newsetting
tent = newsetting.All_Setting('183.6.7.91', 23016, 'pyui_all_market')
import time
timestamp = time.time()
local_time = time.localtime(timestamp)
current_date = time.strftime("%Y-%m-%d", local_time)
# workid 日期前缀,与下面 WORKID_ORG_MAP、主查询保持一致
WORKID_PREFIX = '20260731_咸阳店'
# workid、业务码、门店 mt_org_id
WORKID_ORG_MAP = [
('20260625_喜地大厦', 'chengrenyongpin', '2DYRt4OFVmEgDKBjeKQORQI'),
('20260625_喜地大厦', 'chengrenyongpin', 'JQkbjq43UI6Q8ieG4IRMyQI'),
('20260625_喜地大厦', 'chengrenyongpin', 'VdSfezjBMxGnEPuFItXzqgI'),
('20260625_喜地大厦', 'chengrenyongpin', 'cghDc3UskvfmMJ__xPS5kwI'),
('20260625_喜地大厦', 'chengrenyongpin', '_qS0dKdD8kcsGS2GkMYhugI'),
('20260625_喜地大厦', 'chengrenyongpin', 'O_0Z0YESkN5ZQLDi1lI7xAI'),
('20260625_喜地大厦', 'chengrenyongpin', 'A3EoDTO9S66QC3PFmAGRpAI'),
('20260625_喜地大厦', 'chengrenyongpin', 'IxEV31aiRHiGd0hmfjAWXwI'),
('20260625_喜地大厦', 'chengrenyongpin', 'hncfDIwR39kIapw6JACK7AI'),
('20260625_喜地大厦', 'chengrenyongpin', 'zv-BxAgFLMQwuO9CWz5AegI'),
('20260625_湘域国际', 'chengrenyongpin', 'WLqfF8rDG6Xwklk4w-3NgAI'),
('20260625_湘域国际', 'chengrenyongpin', '9eq-zIsVfrGy56XuwdBwiwI'),
('20260625_湘域国际', 'chengrenyongpin', 'T_svZIbNkeRTTBUNAiPATwI'),
('20260625_湘域国际', 'chengrenyongpin', 'b--gTTBNx6Ox9ZSQpZc9IwI'),
('20260625_湘域国际', 'chengrenyongpin', 'kIQRCqwVfHLVSXRWMATNUAI'),
('20260625_湘域国际', 'chengrenyongpin', 'c7zYrn7xrJAqlAOFc-e7KQI'),
('20260625_湘域国际', 'chengrenyongpin', 'va8PuGdRRHxCD4ZPPeMAfAI'),
('20260625_湘域国际', 'chengrenyongpin', 'l2eExP2iGaBf-ctYDCyy4QI'),
('20260625_湘域国际', 'chengrenyongpin', 'OlkoZKlC9zsbkaDfXG9CWAI'),
('20260625_湘域国际', 'chengrenyongpin', 'l8YdG5_ATPIbU8sXu_WWsgI'),
('20260625_湘域国际', 'chengrenyongpin', 'hobwTnTB4-BMwyshyMofiQI'),
('20260625_湘域国际', 'chengrenyongpin', 'FC3QKOrGcWW2L7ddlRJxHQI'),
('20260625_湘域国际', 'chengrenyongpin', 'MuLbNjkHde4GrnWnN6EBOwI'),
('20260625_湘域国际', 'chengrenyongpin', 'HimeqZraL56vSDdS2k7SMgI'),
('20260625_百脑汇', 'chengrenyongpin', 'E8nMl-Ufc4E8EggOxCLVNAI'),
('20260625_百脑汇', 'chengrenyongpin', 'rmek0D2laO2vEDi1CGIOgwI'),
('20260625_百脑汇', 'chengrenyongpin', 'BYvVak2lk-mh_kwYZBLkVwI'),
('20260625_百脑汇', 'chengrenyongpin', 'Rhdf5dRIYYO-GE6Y5t-YVgI'),
]
TITLE = '一级分类名称,二级分类名称,商品名称,商品ID,SKU ID,upc编码,规格,活动价,原价,商品折扣,商品月售'.split(',')
def sanitize_filename(name):
"""清理文件名非法字符;仅用于保存 Excel,不要用于 SQL"""
name = re.sub(r'[\\/:*?"<>|]', '_', name)
name = name.strip(' .')
return name or 'unnamed'
def workid_folder_name(workid):
if '_' in workid:
return workid.split('_', 1)[1]
return workid
def get_workid(mt_org_id):
for workid, _ti, mt_org_id2 in WORKID_ORG_MAP:
if mt_org_id2 == mt_org_id:
return workid
return None
def to_excel(rows, savename, business_code, workid):
lb = []
for i in rows:
tag1_name, tag2_name, product_name, product_id, skus_id, upccode, spec, price, origin_price, promotion_info, month_saled_content, activity_price = i
if price == origin_price:
lb.append((tag1_name, tag2_name, product_name, product_id, skus_id, upccode, spec, activity_price, origin_price, promotion_info, month_saled_content))
else:
lb.append((tag1_name, tag2_name, product_name, product_id, skus_id, upccode, spec, price, origin_price, promotion_info, month_saled_content))
if not lb:
return False
pa = pandas.DataFrame(lb, columns=TITLE)
folder = workid_folder_name(workid)
save_path = os.path.join('./', current_date, business_code, folder)
os.makedirs(save_path, exist_ok=True)
pa.to_excel(os.path.join(save_path, f'{savename}.xlsx'))
return True
if __name__ == '__main__':
sql = f"""
SELECT DISTINCT shop_name, poi_id_str, workid
FROM `ready_list2_copy1`
WHERE workid LIKE '%{WORKID_PREFIX}%'"""
shopname_list = tent.get_shoppingmalls(sql)
for shop_name, poi_id_str, db_workid in shopname_list:
map_workid = get_workid(poi_id_str)
workid = map_workid or db_workid
if not map_workid:
print(f'[映射外] {shop_name} | {poi_id_str} -> workid={db_workid}')
esc_shop = shop_name.replace("'", "''")
sql2 = f"""
SELECT tag1_name, tag2_name, product_name, product_id, skus_id, upccode, spec,
price, origin_price, promotion_info, month_saled_content, activity_price
FROM `ready_list2_copy1`
WHERE workid like '%{workid}%'
AND poi_id_str = '{poi_id_str}'
AND shop_name = '{esc_shop}'
ORDER BY tag1_name"""
da2 = tent.get_shoppingmalls(sql2)
if not da2:
print(f'[跳过] {workid} | {shop_name} | 无商品数据')
continue
safe_name = sanitize_filename(shop_name)
ok = to_excel(da2, safe_name, 'upc_all_20260626', workid)
if ok:
print(f'[导出] {workid} | {shop_name} -> {safe_name}.xlsx')