歪马送酒每日采集流程(云端出签)
This commit is contained in:
@@ -0,0 +1,317 @@
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import requests
|
||||
import newsetting as ten
|
||||
|
||||
|
||||
# 远端 mtgsig 签名服务(同 8月/海底捞 里那套)
|
||||
SIGN_URL = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
SIGN_TOKEN = 'test_sdfio23923ojbedfojgbouqgew4r32dds'
|
||||
|
||||
|
||||
def get_sign_new1(url, data, dfpid, mtg_origin, open_id, method='POST'):
|
||||
"""调远端服务动态生成 mtgsig"""
|
||||
headers = {"content-type": "application/json", "token": SIGN_TOKEN}
|
||||
body = {
|
||||
"mtg_origin": mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": method,
|
||||
"open_id": open_id, # 微信的open_id
|
||||
}
|
||||
req = requests.post(SIGN_URL, headers=headers, json=body,
|
||||
proxies={'http': None, 'https': None}, verify=False).text
|
||||
print('签名结果:', req[:100])
|
||||
return req
|
||||
|
||||
|
||||
# 模板包库: 从这张表取 is_ok 为 null 的包出签
|
||||
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
|
||||
HEADERS_TABLE = 'waima_search_headers'
|
||||
|
||||
# 任务库: 按 batch 取坐标, 召回结果写回 new_store_id
|
||||
tent_input = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima')
|
||||
TASK_TABLE = 'waima_keyword_input'
|
||||
|
||||
# 代理库: 按任务城市取代理, 没有对应城市代理就直连
|
||||
tent_proxy = ten.All_Setting(host='192.168.5.5', port=3306, db='project_proxy')
|
||||
PROXY_TABLE = 'proxs_list'
|
||||
|
||||
BATCH = datetime.now().strftime('%Y-%m-%d') # 要处理的批次, 默认当天
|
||||
RECALL_PATH = '/api/v1/store/location/recall' # 门店召回接口, 给坐标返回服务门店
|
||||
MAX_NUM = 500 # 单个模板包最多请求次数
|
||||
PACK_USE_NUM = 3 # 每个模板包连发多少次后换下一个包
|
||||
REQ_INTERVAL = 5 # 每个坐标之间的间隔秒数
|
||||
REQ_TIMEOUT = 25 # 单条请求等待秒数
|
||||
|
||||
# 任务表 city -> 首页城市ID(市级行政区划代码)
|
||||
CITY_ID = {
|
||||
'北京市': '110100',
|
||||
'上海市': '310100',
|
||||
'广州市': '440100',
|
||||
'深圳市': '440300',
|
||||
'厦门市': '350200',
|
||||
'成都市': '510100',
|
||||
}
|
||||
|
||||
|
||||
def get_header_rows():
|
||||
"""取未处理的模板包(id / json_data / current_count)"""
|
||||
sql = f'''
|
||||
select id, json_data, current_count from {HEADERS_TABLE} where is_ok is null and current_count < {MAX_NUM}
|
||||
'''
|
||||
rows = tent.get_shoppingmalls(sql)
|
||||
print('未处理模板包 %d 条' % len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def update_header_count(header_id):
|
||||
sql = f'''
|
||||
update {HEADERS_TABLE} set req_count=req_count+1,current_count=current_count+1 where id='{header_id}'
|
||||
'''
|
||||
tent.update_data(sql)
|
||||
|
||||
|
||||
def update_header_is_ok(header_id, is_ok):
|
||||
sql = f'''
|
||||
update {HEADERS_TABLE} set is_ok={is_ok} where id='{header_id}'
|
||||
'''
|
||||
tent.update_data(sql)
|
||||
|
||||
|
||||
def init_pack_pool(header_rows):
|
||||
"""模板包池初始化: unused 是本轮还没用过的包, used 是本轮已抽到的包及已发次数"""
|
||||
pack_pool = {
|
||||
'templates': {},
|
||||
'counts': {},
|
||||
'unused': [],
|
||||
'used': {},
|
||||
'current_id': None,
|
||||
}
|
||||
for header_id, json_data, current_count in header_rows:
|
||||
pack_pool['templates'][header_id] = json.loads(json_data)
|
||||
pack_pool['counts'][header_id] = int(current_count)
|
||||
pack_pool['unused'].append(header_id)
|
||||
return pack_pool
|
||||
|
||||
|
||||
def get_pack(pack_pool):
|
||||
"""取当前模板包; 发满 PACK_USE_NUM 次就从本轮未用的包里随机换一个, 一轮用完重置再随机"""
|
||||
header_id = pack_pool['current_id']
|
||||
if header_id is not None and pack_pool['used'][header_id] < PACK_USE_NUM:
|
||||
return header_id
|
||||
if not pack_pool['unused']:
|
||||
if not pack_pool['used']:
|
||||
return None
|
||||
print(' 一轮模板包都用过, 重置后重新随机')
|
||||
pack_pool['unused'] = list(pack_pool['used'])
|
||||
pack_pool['used'] = {}
|
||||
header_id = random.choice(pack_pool['unused'])
|
||||
pack_pool['unused'].remove(header_id)
|
||||
pack_pool['used'][header_id] = 0
|
||||
pack_pool['current_id'] = header_id
|
||||
return header_id
|
||||
|
||||
|
||||
def consume_pack(pack_pool, header_id):
|
||||
"""成功请求一次: 累加轮换计数和本地 current_count, 到 MAX_NUM 立即出池"""
|
||||
pack_pool['counts'][header_id] += 1
|
||||
pack_pool['used'][header_id] += 1
|
||||
if pack_pool['counts'][header_id] >= MAX_NUM:
|
||||
print(' 模板包 id=%s 已用满 %d 次, 移出包池' % (header_id, MAX_NUM))
|
||||
drop_pack(pack_pool, header_id)
|
||||
|
||||
|
||||
def drop_pack(pack_pool, header_id):
|
||||
"""包被风控/失效: 从包池永久移除, 若是当前包则置空让下一轮重新随机"""
|
||||
pack_pool['templates'].pop(header_id, None)
|
||||
pack_pool['counts'].pop(header_id, None)
|
||||
pack_pool['used'].pop(header_id, None)
|
||||
if header_id in pack_pool['unused']:
|
||||
pack_pool['unused'].remove(header_id)
|
||||
if pack_pool['current_id'] == header_id:
|
||||
pack_pool['current_id'] = None
|
||||
|
||||
|
||||
def get_proxs():
|
||||
"""取城市代理, 返回 {city: prox_data}"""
|
||||
sql = f'''
|
||||
select city, prox_data from {PROXY_TABLE}
|
||||
'''
|
||||
rows = tent_proxy.get_shoppingmalls(sql)
|
||||
proxs = {}
|
||||
for row in rows:
|
||||
city, prox_data = row
|
||||
if type(prox_data) == str:
|
||||
prox_data = json.loads(prox_data)
|
||||
proxs[city] = prox_data
|
||||
print('城市代理 %d 条' % len(proxs))
|
||||
return proxs
|
||||
|
||||
|
||||
def get_city_proxy(city, proxs):
|
||||
"""按城市取代理; 任务表是'深圳市', 代理表是'深圳', 先精确再互相包含; 没有就返回 None 走直连"""
|
||||
proxy_config = proxs.get(city)
|
||||
if bool(proxy_config):
|
||||
return proxy_config
|
||||
for pro_city, prox_data in proxs.items():
|
||||
if pro_city in city or city in pro_city:
|
||||
return prox_data
|
||||
return None
|
||||
|
||||
|
||||
def get_task_groups():
|
||||
"""取该批次所有坐标, 按城市+坐标去重; 同一坐标的多条任务 id 归到一组, 后面一次更新"""
|
||||
sql = f'''
|
||||
select id, city, address, latitude, longitude from {TASK_TABLE} where batch = '{BATCH}' order by id
|
||||
'''
|
||||
rows = tent_input.get_shoppingmalls(sql)
|
||||
print('批次 %s 任务 %d 条' % (BATCH, len(rows)))
|
||||
groups = {}
|
||||
for task_id, city, address, latitude, longitude in rows:
|
||||
# 用四舍五入后的浮点做 key, 避免 '22.53464' 和 '22.534640' 被当成两个坐标
|
||||
key = (city, round(float(latitude), 6), round(float(longitude), 6))
|
||||
if key not in groups:
|
||||
groups[key] = {'city': city, 'address': address, 'latitude': latitude,
|
||||
'longitude': longitude, 'ids': []}
|
||||
groups[key]['ids'].append(task_id)
|
||||
print('去重后坐标 %d 个' % len(groups))
|
||||
return list(groups.values())
|
||||
|
||||
|
||||
def set_loc_headers(header, city, latitude, longitude):
|
||||
"""按任务坐标覆盖模板包里的 homePage* 头; 包里 camelCase 和全小写两种写法都有"""
|
||||
values = {
|
||||
'homepagecityid': CITY_ID[city],
|
||||
'homepagelatitude': latitude,
|
||||
'homepagelongitude': longitude,
|
||||
}
|
||||
for key in list(header):
|
||||
if key.lower() in values:
|
||||
header[key] = values[key.lower()]
|
||||
|
||||
|
||||
def build_body(latitude, longitude):
|
||||
"""按 sdk/lbs/utils.js getLocationPreQueryParams 的构造: identityJson + contentJson 两个 JSON 字符串"""
|
||||
ts = int(time.time() * 1000)
|
||||
identity = {'id': ts, 'medium': '', 'pivot': -1, 'agent': ''}
|
||||
content = {'location': {'latitude': latitude, 'longitude': longitude, 'accuracy': 0, 'id': ts, 'type': 'GCJ02'}}
|
||||
return {
|
||||
'locationPreQuery': {
|
||||
'identityJson': json.dumps(identity, ensure_ascii=False, separators=(',', ':')),
|
||||
'contentJson': json.dumps(content, ensure_ascii=False, separators=(',', ':')),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def req_signed(template, url, body, proxy):
|
||||
"""发一条带签名的请求; body 必须和出签的字节串完全一致, 所以用紧凑 JSON"""
|
||||
header = dict(template['headers'])
|
||||
header.pop('Host', None)
|
||||
header.pop('Content-Length', None)
|
||||
header.pop('Connection', None)
|
||||
|
||||
data_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
|
||||
if 'openId' in header:
|
||||
openId = header['openId']
|
||||
else:
|
||||
openId = header['openid']
|
||||
mtg_origin = json.loads(header['mtgsig'])
|
||||
header['mtgsig'] = get_sign_new1(url, data_str, mtg_origin['a3'], mtg_origin, openId, 'POST')
|
||||
print(' 云端出签 mtgsig:', str(header['mtgsig'])[:60])
|
||||
return requests.post(url, headers=header, data=data_str.encode('utf-8'),
|
||||
timeout=REQ_TIMEOUT, proxies=proxy)
|
||||
|
||||
|
||||
def req_recall(template, group, proxy):
|
||||
"""按坐标召回门店; host 和 query 沿用模板包, path 换成召回接口"""
|
||||
base_url = template['url'].split('/api/')[0]
|
||||
query = template['url'].split('?', 1)[1]
|
||||
url = base_url + RECALL_PATH + '?' + query
|
||||
body = build_body(float(group['latitude']), float(group['longitude']))
|
||||
return req_signed(template, url, body, proxy)
|
||||
|
||||
|
||||
def update_new_store_id(id_list, poi_id_str):
|
||||
"""把召回到的 poiIdStr 写回这一组任务行"""
|
||||
id_str = ','.join(str(task_id) for task_id in id_list)
|
||||
sql = f'''
|
||||
update {TASK_TABLE} set new_store_id='{poi_id_str}' where id in ({id_str})
|
||||
'''
|
||||
tent_input.update_data(sql)
|
||||
|
||||
|
||||
def req_task_group(pack_pool, group, proxy):
|
||||
"""一个坐标召回一次; 包被风控就出池换包重试, 返回 True 表示这组处理完了"""
|
||||
last_header_id = None
|
||||
while True:
|
||||
header_id = get_pack(pack_pool)
|
||||
if header_id is None:
|
||||
print(' 没有可用的模板包')
|
||||
return False
|
||||
template = pack_pool['templates'][header_id]
|
||||
if header_id != last_header_id:
|
||||
set_loc_headers(template['headers'], group['city'], str(int(round(float(group['latitude']) * 1000000))),
|
||||
str(int(round(float(group['longitude']) * 1000000))))
|
||||
print(' 当前模板包 id=%s' % header_id)
|
||||
last_header_id = header_id
|
||||
|
||||
resp = req_recall(template, group, proxy)
|
||||
status = resp.status_code
|
||||
print(' 召回 status=%s' % status)
|
||||
if status == 403:
|
||||
print(' 403, 账号可能被风控, 标记 is_ok=403')
|
||||
update_header_is_ok(header_id, 403)
|
||||
drop_pack(pack_pool, header_id)
|
||||
last_header_id = None
|
||||
continue
|
||||
if status != 200:
|
||||
print(' 响应体:', resp.text[:500])
|
||||
update_header_is_ok(header_id, status)
|
||||
drop_pack(pack_pool, header_id)
|
||||
last_header_id = None
|
||||
continue
|
||||
|
||||
update_header_count(header_id)
|
||||
consume_pack(pack_pool, header_id)
|
||||
|
||||
inner = resp.json()
|
||||
page_data = inner['data']
|
||||
if not page_data:
|
||||
print(' 该坐标没有召回门店, 响应:', resp.text[:300])
|
||||
return True
|
||||
poi_id_str = page_data['poiIdStr']
|
||||
print(' 门店=%s 距离=%s 城市=%s poiIdStr=%s' % (
|
||||
page_data['wmPoiName'], page_data['distanceToUser'], page_data['cityId'], poi_id_str))
|
||||
update_new_store_id(group['ids'], poi_id_str)
|
||||
print(' 回写 %d 行: 任务id=%s' % (len(group['ids']), group['ids'][:5]))
|
||||
return True
|
||||
|
||||
|
||||
def run_recall():
|
||||
header_rows = get_header_rows()
|
||||
if not header_rows:
|
||||
print('没有可用的模板包')
|
||||
return
|
||||
pack_pool = init_pack_pool(header_rows)
|
||||
proxs = get_proxs()
|
||||
groups = get_task_groups()
|
||||
for group in groups:
|
||||
proxy = get_city_proxy(group['city'], proxs)
|
||||
if not proxy:
|
||||
print(' 城市=%s 没有对应代理, 直连' % group['city'])
|
||||
print('=== %s %s 坐标=%s,%s 任务%d行 proxy=%s ===' % (
|
||||
group['city'], group['address'], group['latitude'], group['longitude'], len(group['ids']), proxy))
|
||||
done = req_task_group(pack_pool, group, proxy)
|
||||
if not done:
|
||||
print('模板包池已空, 停止')
|
||||
break
|
||||
time.sleep(REQ_INTERVAL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_recall()
|
||||
Reference in New Issue
Block a user