Files
2026-10-11 19:29:49 +08:00

503 lines
21 KiB
Python

import os
import re
import sys
import json
import time
import datetime
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import newsetting as ten
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima') # 任务库, 只读
COUPON_VIEW = 'waima_coupon_summary' # 券汇总视图, 汇总表.sql 里建
KEYWORD_VIEW = 'waima_keyword_summary' # 关键词汇总视图, 汇总表.sql 里建
PAGE_TABLE = 'waima_page_summary' # 页级汇总表, 采集脚本/补数脚本往里写
INPUT_TABLE = 'waima_keyword_input' # 只有它带城市, 用来做城市筛选
COUPON_RAW = 'waima_coupon_detail' # 抽屉里看商品明细时才回读
SEARCH_RAW = 'waima_keyword_search'
PORT = 18765 # 看板端口(8765 被百度输入法占了)
LIVE_SECONDS = 300 # 最近 5 分钟有新页入库就算"采集中"
CACHE_SECONDS = 20 # 汇总数据缓存秒数, 看板 30 秒刷一次
WEB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'web', 'dist') # 前端构建产物
TIME_FMT = '%Y-%m-%d %H:%M:%S'
BATCH_RE = re.compile(r'^[\w\-]{1,64}$') # 批次/店铺id 只允许字母数字下划线横杠
app = FastAPI()
table_cache = {'time': 0, 'data': None} # 汇总数据缓存
def check_text(value, name):
if value and not BATCH_RE.match(value):
raise HTTPException(400, '%s 参数不合法' % name)
return value
def check_time(value, name):
if not value:
return None
try:
return datetime.datetime.strptime(value, TIME_FMT)
except ValueError:
raise HTTPException(400, '%s 时间格式应为 %s' % (name, TIME_FMT))
def fmt_time(value):
return value.strftime(TIME_FMT) if value else None
def sql_text(value):
"""自由文本(关键词)拼进 SQL 前转义, 防单引号截断"""
return str(value).replace('\\', '\\\\').replace("'", "''")
def split_spu(value):
"""A 表里 spu_ids 是逗号拼接的串"""
return [spu for spu in (value or '').split(',') if spu]
def get_cache():
"""汇总视图和 A 表都很小, 一次读回来在内存里筛选聚合; rawdata 只在看单个券/关键词时才读"""
if table_cache['data'] and time.time() - table_cache['time'] < CACHE_SECONDS:
return table_cache['data']
coupon_sql = f'''
select item_id, store_id, coupon_id, coupon_name, type_doc, category, price, limit_text, condition_text,
use_doc, use_rules, tabId, is_ok, current_page, created_at, batch, store_name,
page_count, product_count, last_page, last_has_more, last_time, status from {COUPON_VIEW}
'''
coupon_rows = []
for row in tent.get_shoppingmalls(coupon_sql):
coupon_rows.append({
'id': row[0], 'store_id': row[1], 'coupon_id': row[2], 'name': row[3], 'type_doc': row[4],
'category': row[5], 'price': row[6], 'limit_text': row[7], 'condition_text': row[8],
'use_doc': row[9], 'use_rules': json.loads(row[10]), 'tabId': row[11], 'is_ok': row[12],
'current_page': row[13] or 0, 'created_at': row[14], 'batch': row[15], 'store_name': row[16],
'page_count': int(row[17] or 0), 'product_count': int(row[18] or 0), 'last_page': row[19],
'last_has_more': row[20], 'last_time': row[21], 'status': row[22],
})
keyword_sql = f'''
select task_id, batch, store_id, store_name, keyword, plan_page, current_page, total_num,
created_at, updated_at, saved_pages, product_count, last_time, status from {KEYWORD_VIEW}
'''
keyword_rows = []
for row in tent.get_shoppingmalls(keyword_sql):
keyword_rows.append({
'id': row[0], 'batch': row[1], 'store_id': row[2], 'store_name': row[3], 'keyword': row[4],
'page': int(row[5]), 'current_page': int(row[6] or 0), 'total_num': row[7],
'created_at': row[8], 'updated_at': row[9], 'saved_pages': int(row[10] or 0),
'product_count': int(row[11] or 0), 'last_time': row[12], 'status': row[13],
})
page_sql = f'''
select source, batch, store_id, biz_id, page, product_count, has_more, total_num, spu_ids, snapshot_time from {PAGE_TABLE}
'''
page_rows = []
for row in tent.get_shoppingmalls(page_sql):
page_rows.append({
'source': row[0], 'batch': row[1], 'store_id': row[2], 'biz_id': row[3], 'page': int(row[4]),
'product_count': int(row[5] or 0), 'has_more': int(row[6] or 0), 'total_num': row[7],
'spu_ids': row[8], 'time': row[9],
})
# (来源, 批次, 店铺, 券id或关键词) -> 该实体的全部页, 按页号排序
pages_by_key = {}
for row in page_rows:
pages_by_key.setdefault((row['source'], row['batch'], row['store_id'], row['biz_id']), []).append(row)
for rows in pages_by_key.values():
rows.sort(key=lambda x: x['page'])
# 店铺 -> 城市, 只有关键词任务表带城市
store_city = {}
for row in tent.get_shoppingmalls(f'select store_id, city from {INPUT_TABLE}'):
store_city[row[0]] = row[1]
data = {
'coupons': coupon_rows, 'keywords': keyword_rows, 'pages': page_rows,
'pages_by_key': pages_by_key, 'store_city': store_city,
}
table_cache['data'] = data
table_cache['time'] = time.time()
return data
def clean_product(item):
return {
'spu_id': str(item['spuId']), 'name': item['spuName'], 'picture': item['picture'],
'price': item['price'], 'origin_price': item['originPrice'], 'activity_price': item['activityPrice'],
'after_coupon': item['priceAfterCoupon'], 'unit': item['unit'],
}
def get_entity_products(table_name, biz_col, store_id, biz_id):
"""取单个券/关键词的原始页商品, 只查这一个实体.
清表重跑会留下同页多行, 按页号取最后写入的那行(id 最大)"""
check_text(store_id, 'store_id')
raw_sql = f'''
select page, snapshot_time, rawdata from {table_name} where store_id='{store_id}' and {biz_col}='{sql_text(biz_id)}' order by page, id
'''
page_dict = {}
for page_no, snapshot_time, rawdata in tent.get_shoppingmalls(raw_sql):
page_data = json.loads(rawdata)['data']
if table_name == COUPON_RAW:
# 券商品页的商品现在在 cards[].data 里(products 是空的), 老数据的页才在 products
items = [card['data'] for card in page_data['cards']]
if not items:
items = page_data['products']
products = [clean_product(item) for item in items]
has_more = page_data['hasMore']
total_num = None
else:
products = [clean_product(card['data']) for card in page_data['cards']]
has_more = page_data['hasNextPage']
total_num = page_data['totalNum']
page_dict[int(page_no)] = {
'page': int(page_no), 'time': fmt_time(snapshot_time), 'has_more': bool(has_more),
'total_num': total_num, 'products': products,
}
return [page_dict[key] for key in sorted(page_dict)]
def get_batches(data):
batch_set = set()
for name in ['pages', 'coupons', 'keywords']:
for row in data[name]:
batch_set.add(row['batch'])
return sorted(batch_set, reverse=True)
def get_filter(mode, batch, start, end, city, store_id):
"""mode=batch 按批次; mode=range 按 [start, end] 时间段; 都没给就取最新批次"""
check_text(batch, 'batch')
check_text(store_id, 'store_id')
start_time = check_time(start, 'start')
end_time = check_time(end, 'end')
data = get_cache()
if mode == 'range':
if not start_time or not end_time:
raise HTTPException(400, '时间段模式需要 start 和 end')
if start_time > end_time:
raise HTTPException(400, 'start 不能晚于 end')
return {'mode': 'range', 'batch': None, 'start': start_time, 'end': end_time, 'city': city, 'store_id': store_id}
batch_list = get_batches(data)
if not batch:
batch = batch_list[0] if batch_list else ''
return {'mode': 'batch', 'batch': batch, 'start': None, 'end': None, 'city': city, 'store_id': store_id}
def get_prev_filter(filter_data):
"""上一周期: 批次取前一个批次, 时间段取等长的前一段"""
if filter_data['mode'] == 'range':
span = filter_data['end'] - filter_data['start']
prev = dict(filter_data)
prev['end'] = filter_data['start'] - datetime.timedelta(seconds=1)
prev['start'] = prev['end'] - span
return prev
batch_list = get_batches(get_cache())
if filter_data['batch'] not in batch_list:
return None
index = batch_list.index(filter_data['batch'])
if index + 1 >= len(batch_list):
return None
prev = dict(filter_data)
prev['batch'] = batch_list[index + 1]
return prev
def match_store(filter_data, store_id, data):
if filter_data['store_id'] and store_id != filter_data['store_id']:
return False
if filter_data['city'] and data['store_city'].get(store_id) != filter_data['city']:
return False
return True
def in_time(filter_data, value):
return value is not None and filter_data['start'] <= value <= filter_data['end']
def pick_pages(filter_data, data, source):
"""按筛选取 coupon / search 的页"""
rows = []
for row in data['pages']:
if row['source'] != source:
continue
if not match_store(filter_data, row['store_id'], data):
continue
if filter_data['mode'] == 'batch' and row['batch'] != filter_data['batch']:
continue
if filter_data['mode'] == 'range' and not in_time(filter_data, row['time']):
continue
rows.append(row)
return rows
def get_coupon_pages(coupon, data):
"""某张券的全部已采页"""
return data['pages_by_key'].get(('coupon', coupon['batch'], coupon['store_id'], coupon['coupon_id']), [])
def get_keyword_pages(keyword_row, data):
"""某个关键词的全部已采页"""
return data['pages_by_key'].get(('search', keyword_row['batch'], keyword_row['store_id'], keyword_row['keyword']), [])
def pick_coupons(filter_data, data):
"""返回 [(券, 全部页, 筛选范围内的页)]"""
result = []
for coupon in data['coupons']:
if not match_store(filter_data, coupon['store_id'], data):
continue
if filter_data['mode'] == 'batch' and coupon['batch'] != filter_data['batch']:
continue
all_pages = get_coupon_pages(coupon, data)
if filter_data['mode'] == 'range':
range_pages = [row for row in all_pages if in_time(filter_data, row['time'])]
# 时间段: 券在段内没页, 但本身就是这段建的, 也算进来
if not range_pages and not in_time(filter_data, coupon['created_at']):
continue
else:
range_pages = all_pages
result.append((coupon, all_pages, range_pages))
return result
def pick_keywords(filter_data, data):
result = []
for row in data['keywords']:
if not match_store(filter_data, row['store_id'], data):
continue
if filter_data['mode'] == 'batch' and row['batch'] != filter_data['batch']:
continue
# 时间段: 任务在段内存在过且段内有过更新
if filter_data['mode'] == 'range' and not (row['created_at'] <= filter_data['end'] and row['updated_at'] >= filter_data['start']):
continue
result.append(row)
return result
def count_summary(filter_data, data):
coupon_list = pick_coupons(filter_data, data)
status_count = {'done': 0, 'empty': 0, 'running': 0, 'pending': 0}
coupon_pages = 0
coupon_products = 0
coupon_spu = set()
for coupon, all_pages, range_pages in coupon_list:
status_count[coupon['status']] += 1
coupon_pages += len(range_pages)
for row in range_pages:
coupon_products += row['product_count']
coupon_spu.update(split_spu(row['spu_ids']))
keyword_list = pick_keywords(filter_data, data)
keyword_count = {'done': 0, 'running': 0, 'pending': 0}
for row in keyword_list:
keyword_count[row['status']] += 1
search_rows = pick_pages(filter_data, data, 'search')
search_products = 0
search_spu = set()
for row in search_rows:
search_products += row['product_count']
search_spu.update(split_spu(row['spu_ids']))
# 时间段模式: 段内真有页入库的券才算段内采集过
if filter_data['mode'] == 'range':
coupon_collected = len([1 for _, _, range_pages in coupon_list if range_pages])
else:
coupon_collected = len(coupon_list) - status_count['pending']
return {
'coupon_total': len(coupon_list),
'coupon_collected': coupon_collected,
'coupon_status': status_count,
'coupon_pages': coupon_pages,
'coupon_products': coupon_products,
'coupon_spu': len(coupon_spu),
'keyword_total': len(keyword_list),
'keyword_status': keyword_count,
'search_pages': len(search_rows),
'search_products': search_products,
'search_spu': len(search_spu),
'product_spu': len(coupon_spu | search_spu),
}
def get_live(data):
"""最近一次页入库时间, 以及是否还在采集"""
time_list = [row['time'] for row in data['pages'] if row['time']]
if not time_list:
return {'last_time': None, 'live': False}
last_time = max(time_list)
return {'last_time': fmt_time(last_time), 'live': (datetime.datetime.now() - last_time).total_seconds() < LIVE_SECONDS}
@app.get('/api/meta')
def api_meta():
data = get_cache()
batch_list = []
for batch in get_batches(data):
time_list = [row['time'] for row in data['pages'] if row['batch'] == batch and row['time']]
time_list += [row['last_time'] for row in data['coupons'] if row['batch'] == batch and row['last_time']]
time_list += [row['updated_at'] for row in data['keywords'] if row['batch'] == batch and row['updated_at']]
batch_list.append({
'batch': batch,
'first_time': fmt_time(min(time_list)) if time_list else None,
'last_time': fmt_time(max(time_list)) if time_list else None,
})
store_dict = {}
for row in data['keywords'] + data['coupons']:
store_dict[row['store_id']] = {'store_id': row['store_id'], 'store_name': row['store_name'], 'city': data['store_city'].get(row['store_id'])}
city_list = sorted(set(store['city'] for store in store_dict.values() if store['city']))
return {'batches': batch_list, 'cities': city_list, 'stores': list(store_dict.values()), **get_live(data)}
@app.get('/api/summary')
def api_summary(mode: str = 'batch', batch: str = '', start: str = '', end: str = '', city: str = '', store_id: str = ''):
filter_data = get_filter(mode, batch, start, end, city, store_id)
data = get_cache()
prev_filter = get_prev_filter(filter_data)
return {
'current': count_summary(filter_data, data),
'prev': count_summary(prev_filter, data) if prev_filter else None,
'prev_label': (prev_filter['batch'] if prev_filter and prev_filter['mode'] == 'batch' else ('上一时段' if prev_filter else None)),
'batch': filter_data['batch'],
**get_live(data),
}
@app.get('/api/timeline')
def api_timeline(mode: str = 'batch', batch: str = '', start: str = '', end: str = '', city: str = '', store_id: str = ''):
filter_data = get_filter(mode, batch, start, end, city, store_id)
data = get_cache()
coupon_rows = [row for _, _, range_pages in pick_coupons(filter_data, data) for row in range_pages]
search_rows = pick_pages(filter_data, data, 'search')
time_list = [row['time'] for row in coupon_rows + search_rows]
if filter_data['mode'] == 'range':
begin_time, end_time = filter_data['start'], filter_data['end']
elif time_list:
begin_time, end_time = min(time_list), max(time_list)
else:
return {'unit': 'hour', 'buckets': []}
# 跨度两天以内按小时, 否则按天
unit = 'hour' if (end_time - begin_time).total_seconds() <= 2 * 86400 else 'day'
if unit == 'hour':
cursor = begin_time.replace(minute=0, second=0, microsecond=0)
step = datetime.timedelta(hours=1)
key_fmt = '%Y-%m-%d %H:00'
else:
cursor = begin_time.replace(hour=0, minute=0, second=0, microsecond=0)
step = datetime.timedelta(days=1)
key_fmt = '%Y-%m-%d'
bucket_dict = {}
while cursor <= end_time:
bucket_dict[cursor.strftime(key_fmt)] = {'time': cursor.strftime(key_fmt), 'coupon_pages': 0, 'search_pages': 0}
cursor += step
for row in coupon_rows:
bucket_dict[row['time'].strftime(key_fmt)]['coupon_pages'] += 1
for row in search_rows:
bucket_dict[row['time'].strftime(key_fmt)]['search_pages'] += 1
return {'unit': unit, 'buckets': list(bucket_dict.values())}
@app.get('/api/coupons')
def api_coupons(mode: str = 'batch', batch: str = '', start: str = '', end: str = '', city: str = '', store_id: str = ''):
filter_data = get_filter(mode, batch, start, end, city, store_id)
data = get_cache()
coupon_list = pick_coupons(filter_data, data)
result = []
for coupon, all_pages, range_pages in coupon_list:
page_list = []
for row in all_pages:
page_list.append({
'page': row['page'], 'products': row['product_count'], 'time': fmt_time(row['time']),
'in_range': True if filter_data['mode'] == 'batch' else in_time(filter_data, row['time']),
})
result.append({
'id': coupon['id'], 'coupon_id': coupon['coupon_id'], 'name': coupon['name'],
'type_doc': coupon['type_doc'], 'category': coupon['category'], 'price': coupon['price'],
'limit_text': coupon['limit_text'], 'condition_text': coupon['condition_text'], 'use_doc': coupon['use_doc'],
'store_id': coupon['store_id'], 'store_name': coupon['store_name'], 'batch': coupon['batch'],
'status': coupon['status'], 'page_count': coupon['page_count'], 'product_count': coupon['product_count'],
'pages': page_list, 'last_time': fmt_time(coupon['last_time']),
})
return {'coupons': result}
@app.get('/api/coupons/{item_id}/pages')
def api_coupon_pages(item_id: int):
data = get_cache()
coupon_list = [coupon for coupon in data['coupons'] if coupon['id'] == item_id]
if not coupon_list:
raise HTTPException(404, '券不存在')
coupon = coupon_list[0]
page_list = get_entity_products(COUPON_RAW, 'coupon_id', coupon['store_id'], coupon['coupon_id'])
return {
'coupon': {
'id': coupon['id'], 'coupon_id': coupon['coupon_id'], 'name': coupon['name'], 'type_doc': coupon['type_doc'],
'price': coupon['price'], 'limit_text': coupon['limit_text'], 'condition_text': coupon['condition_text'],
'use_doc': coupon['use_doc'], 'use_rules': coupon['use_rules'], 'store_name': coupon['store_name'],
'batch': coupon['batch'], 'status': coupon['status'],
},
'pages': page_list,
}
@app.get('/api/keywords')
def api_keywords(mode: str = 'batch', batch: str = '', start: str = '', end: str = '', city: str = '', store_id: str = ''):
filter_data = get_filter(mode, batch, start, end, city, store_id)
data = get_cache()
result = []
for row in pick_keywords(filter_data, data):
result.append({
'id': row['id'], 'keyword': row['keyword'], 'store_id': row['store_id'], 'store_name': row['store_name'],
'batch': row['batch'], 'page': row['page'], 'current_page': row['current_page'],
'total_num': row['total_num'], 'status': row['status'],
'saved_pages': row['saved_pages'], 'product_count': row['product_count'],
'updated_at': fmt_time(row['updated_at']),
})
return {'keywords': result}
@app.get('/api/keywords/{task_id}/pages')
def api_keyword_pages(task_id: int):
data = get_cache()
task_list = [row for row in data['keywords'] if row['id'] == task_id]
if not task_list:
raise HTTPException(404, '关键词任务不存在')
task_row = task_list[0]
page_list = get_entity_products(SEARCH_RAW, 'keyword', task_row['store_id'], task_row['keyword'])
return {
'keyword': {
'id': task_row['id'], 'keyword': task_row['keyword'], 'store_name': task_row['store_name'],
'batch': task_row['batch'], 'page': task_row['page'], 'current_page': task_row['current_page'],
'total_num': task_row['total_num'], 'status': task_row['status'],
},
'pages': page_list,
}
# 前端构建产物; 先 npm run build 再起服务
if os.path.isdir(WEB_DIR):
app.mount('/assets', StaticFiles(directory=os.path.join(WEB_DIR, 'assets')), name='assets')
@app.get('/{path:path}')
def web_index(path: str):
file_path = os.path.join(WEB_DIR, path)
if path and os.path.isfile(file_path) and os.path.abspath(file_path).startswith(os.path.abspath(WEB_DIR)):
return FileResponse(file_path)
return FileResponse(os.path.join(WEB_DIR, 'index.html'))
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=PORT)