# -*- coding: utf-8 -*- from __future__ import annotations """药品搜索多线程。逻辑同 部分.py,线程数改 WORKERS。""" import importlib.util import threading from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path # ==================== 运行参数(改这里) ==================== WORKERS = 5 # ============================================================ _src = Path(__file__).resolve().with_name('部分.py') _spec = importlib.util.spec_from_file_location('drug_search_one', _src) one = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(one) db_lock = threading.Lock() stop_event = threading.Event() mark_lock = threading.Lock() packet_marked = False def handle(task, packet_index, use_url, use_params, use_payload, base_headers, by_admin, by_name): global packet_marked if stop_event.is_set(): return 'stopped' parent_id, keyword, lat, lng, batch, city = task ci = one.lookup_ci(city, by_admin, by_name) if not ci: print(f'任务 {parent_id} 找不到城市id city={city},跳过') return 'skip' print(f'任务 {parent_id} {city} ci={ci} {keyword} lng={lng} lat={lat}') headers = dict(base_headers) response = one.run(keyword, lng, lat, headers, use_url, use_params, use_payload, parent_id, ci) dead = one.packet_dead_code(response) if dead is not None: stop_event.set() with mark_lock: if not packet_marked: with db_lock: one.mark_packet(packet_index, dead) packet_marked = True print(f'任务 {parent_id} 返回 {dead},包已更新,停止') return 'dead' data = response.text try: body = one.json.loads(data) except one.json.JSONDecodeError: print(f'任务 {parent_id} 响应不是 json,不入库') return 'bad' if body.get('code') != 0: print(f'任务 {parent_id} code={body.get("code")} msg={body.get("msg")} 不入库') return 'bad' with db_lock: one.save_task(parent_id, data, batch) one.tent.update_data(f'update target_adcode set `is_search`=1 where id={int(parent_id)}') one.add_req_count(packet_index) print(f'任务 {parent_id} 已入库') return 'ok' def main(): loaded = one.load_packet() if not loaded: return packet_index, packet = loaded use_url = packet['url'] use_params = packet['params'] use_payload = packet['payload'] base_headers = packet['headers'] by_admin, by_name = one.load_city_ci(Path(__file__).resolve().parent / 'id.json') task_all = one.get_task() or [] print(f'任务 {len(task_all)} 条,线程 {WORKERS}') ok = 0 with ThreadPoolExecutor(max_workers=WORKERS) as pool: futures = [ pool.submit( handle, task, packet_index, use_url, use_params, use_payload, base_headers, by_admin, by_name, ) for task in task_all ] for fut in as_completed(futures): try: result = fut.result() except Exception as e: print(f'任务异常: {e}') continue if result == 'ok': ok += 1 if stop_event.is_set(): for pending in futures: pending.cancel() break print(f'结束,成功入库 {ok} 条') if __name__ == '__main__': main()