From 1c95f88e93c328e975cebe604166a43cde6985bd Mon Sep 17 00:00:00 2001 From: RBP15P Date: Thu, 10 Sep 2026 17:18:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BC=82=E6=AD=A5=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=A5=BC=E5=AE=87=E5=B9=B6=E5=AE=9E=E6=97=B6=E5=8D=95=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E5=86=99=E5=85=A5CSV?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GetNRBuildingsData.py | 254 ++++++++++++++++++++++------------ README.md | 10 +- requirements-nr-buildings.txt | 1 + tests/test_nr_buildings.py | 157 +++++++++++++++++++++ 4 files changed, 331 insertions(+), 91 deletions(-) create mode 100644 requirements-nr-buildings.txt create mode 100644 tests/test_nr_buildings.py diff --git a/GetNRBuildingsData.py b/GetNRBuildingsData.py index 3cff181..a287a6b 100644 --- a/GetNRBuildingsData.py +++ b/GetNRBuildingsData.py @@ -1,18 +1,19 @@ -"""从坐标 CSV 批量查询楼宇 WFS,汇总 properties 为 CSV。独立运行,无第三方依赖。""" +"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。""" +import asyncio +from concurrent.futures import ThreadPoolExecutor import csv from decimal import Decimal, InvalidOperation -import gzip from itertools import islice import json from pathlib import Path +import signal import tempfile -import time -from urllib.error import HTTPError, URLError from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit, quote -from urllib.request import HTTPRedirectHandler, Request, build_opener import xml.etree.ElementTree as ET +import aiohttp + # 填完整 WFS URL(包含 ak、sig 等参数);原 CQL_FILTER 会自动替换。 # 请粘贴纯 URL,不含 curl、CMD 的 ^ 转义或 Markdown 链接外壳。 @@ -29,10 +30,11 @@ LONGITUDE_COLUMN = "经度" LATITUDE_COLUMN = "维度" # 源文件实际写的是“维度”。 GEOMETRY_FIELD = "the_geom" START_ROW = 1 # 从第几条数据开始,不计表头。 -LIMIT = 10 # 初次只查 10 条;确认结果后改成 None 处理剩余全部。 +LIMIT = 1000 # 最多查询的坐标数;None 表示处理剩余全部。 +CONCURRENCY = 8 # 并发查询协程数;CSV 始终只由一个线程写入。 TIMEOUT = 30 # 每次请求超时秒数。 MAX_RETRIES = 2 # 网络异常、429 或 5xx 的重试次数;空结果不重试。 -REQUEST_INTERVAL = 0.2 # 两个坐标之间的等待秒数。 +REQUEST_INTERVAL = 0.2 # 每个查询协程两次请求之间的等待秒数。 PROGRESS_EVERY = 100 QUERY_COLUMNS = ["查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"] @@ -45,11 +47,6 @@ class AuthenticationError(QueryError): pass -class NoRedirect(HTTPRedirectHandler): - def redirect_request(self, request, file_pointer, code, message, headers, new_url): - return None - - def coordinate(value, lower, upper): try: number = Decimal(str(value).strip()) @@ -68,31 +65,24 @@ def query_url(longitude, latitude): return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(params, quote_via=quote), "")) -def fetch_features(opener, longitude, latitude): - request = Request(query_url(longitude, latitude), headers={ - "Cookie": COOKIES.strip(), "Referer": REFERER, - "Accept": "application/json", "Accept-Encoding": "gzip", - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/155.0", - }) +async def fetch_features(session, longitude, latitude): for attempt in range(MAX_RETRIES + 1): try: - with opener.open(request, timeout=TIMEOUT) as response: - content = response.read() - if response.headers.get("Content-Encoding", "").lower() == "gzip": - content = gzip.decompress(content) + async with session.get(query_url(longitude, latitude), allow_redirects=False) as response: + status = response.status + if status in (301, 302, 303, 307, 308, 401, 403): + raise AuthenticationError(f"HTTP {status},请检查 URL、Cookies 或登录是否过期") + if status >= 400: + if attempt < MAX_RETRIES and (status == 429 or status >= 500): + await response.read() + await asyncio.sleep(attempt + 1) + continue + raise QueryError(f"HTTP {status}") + content = await response.read() break - except HTTPError as exc: - status = exc.code - exc.close() - if status in (301, 302, 303, 307, 308, 401, 403): - raise AuthenticationError(f"HTTP {status},请检查 URL、Cookies 或登录是否过期") from None - if attempt < MAX_RETRIES and (status == 429 or status >= 500): - time.sleep(attempt + 1) - continue - raise QueryError(f"HTTP {status}") from None - except (URLError, TimeoutError, OSError): + except (aiohttp.ClientError, asyncio.TimeoutError, OSError): if attempt < MAX_RETRIES: - time.sleep(attempt + 1) + await asyncio.sleep(attempt + 1) continue raise QueryError("网络连接失败或超时,请检查网络、证书及服务状态") from None try: @@ -126,7 +116,57 @@ def csv_value(value): return value -def main(): +class StreamingCsvWriter: + """所有方法只在同一个专用线程调用,包括建表头、扩列、追加和关闭。""" + + def __init__(self, output_path): + self.path = output_path + self.fields = list(QUERY_COLUMNS) + self.file = self.path.open("w", encoding=OUTPUT_ENCODING, newline="") + try: + self.writer = csv.DictWriter(self.file, fieldnames=self.fields) + self.writer.writeheader() + self.file.flush() + except BaseException: + self.file.close() + raise + + def extend_fields(self, fields): + self.file.flush() + temporary = None + try: + # 后出现的字段需补到旧行;独占写线程执行原子替换,其他协程只入队。 + with tempfile.NamedTemporaryFile("w", encoding=OUTPUT_ENCODING, newline="", delete=False, + dir=self.path.parent, prefix=f".{self.path.name}.", suffix=".tmp") as target: + temporary = Path(target.name) + writer = csv.DictWriter(target, fieldnames=fields) + writer.writeheader() + with self.path.open("r", encoding=OUTPUT_ENCODING, newline="") as source: + writer.writerows(csv.DictReader(source)) + self.file.close() + temporary.replace(self.path) + self.fields = fields + self.file = self.path.open("a", encoding=OUTPUT_ENCODING, newline="") + self.writer = csv.DictWriter(self.file, fieldnames=self.fields) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + def write_result(self, result): + metadata, features = result + rows = [{**metadata, "要素ID": feature.get("id", ""), **feature["properties"]} + for feature in features] if features else [metadata] + fields = list(dict.fromkeys([*self.fields, *(key for row in rows for key in row)])) + if fields != self.fields: + self.extend_fields(fields) + self.writer.writerows({key: csv_value(value) for key, value in row.items()} for row in rows) + self.file.flush() + + def close(self): + self.file.close() + + +async def async_main(*, handle_signals=True): parts = urlsplit(URL.strip()) if parts.scheme not in ("http", "https") or not parts.netloc or not COOKIES.strip(): raise ValueError("请先在脚本顶部填写完整 URL 和 COOKIES") @@ -134,74 +174,108 @@ def main(): raise ValueError("START_ROW、LIMIT 必须大于 0;LIMIT 可设为 None") if TIMEOUT <= 0 or MAX_RETRIES < 0 or REQUEST_INTERVAL < 0 or PROGRESS_EVERY < 1: raise ValueError("超时和进度间隔须大于0,重试次数和请求间隔须非负") + if not isinstance(CONCURRENCY, int) or CONCURRENCY < 1: + raise ValueError("CONCURRENCY 必须是大于0的整数") input_path, output_path = Path(INPUT_CSV), Path(OUTPUT_CSV) if input_path.resolve() == output_path.resolve(): raise ValueError("输出文件不能覆盖输入坐标文件") output_path.parent.mkdir(parents=True, exist_ok=True) - opener = build_opener(NoRedirect()) - property_fields = [] - property_seen = set() counts = {"查询坐标": 0, "命中坐标": 0, "未命中坐标": 0, "失败坐标": 0, "楼宇结果行": 0} interrupted = False stop_reason = "" - with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source, \ - tempfile.TemporaryFile(mode="w+", encoding="utf-8", newline="") as spool: + stop = asyncio.Event() + results = asyncio.Queue(maxsize=CONCURRENCY * 2) + loop = asyncio.get_running_loop() + + def request_stop(): + nonlocal interrupted + interrupted = True + stop.set() + print("停止领取新坐标,等待进行中的请求和写入完成……", flush=True) + + async def query_worker(session, selected): + nonlocal stop_reason + while not stop.is_set(): + # 同一事件循环中读取下一行,无 await,不会并发推进 CSV 迭代器。 + point = next(selected, None) + if point is None: + break + metadata = {"查询序号": point.get(ID_COLUMN), "查询经度": point.get(LONGITUDE_COLUMN), + "查询纬度": point.get(LATITUDE_COLUMN), "命中数量": 0, "要素ID": "", "错误信息": ""} + features = [] + try: + lon = coordinate(point.get(LONGITUDE_COLUMN), -180, 180) + lat = coordinate(point.get(LATITUDE_COLUMN), -90, 90) + features = await fetch_features(session, lon, lat) + if any(set(feature["properties"]) & set(QUERY_COLUMNS) for feature in features): + raise QueryError("properties 字段与查询信息列重名") + metadata["查询状态"] = "成功" if features else "未命中" + metadata["命中数量"] = len(features) + except ValueError as exc: + features = [] + metadata.update(查询状态="坐标无效", 错误信息=str(exc)) + except QueryError as exc: + features = [] + metadata.update(查询状态="请求失败", 错误信息=str(exc)) + if isinstance(exc, AuthenticationError): + stop_reason = stop_reason or str(exc) + stop.set() + await results.put((metadata, features)) + if REQUEST_INTERVAL and not stop.is_set(): + await asyncio.sleep(REQUEST_INTERVAL) + await results.put(None) + + async def write_results(executor): + writer = await loop.run_in_executor(executor, StreamingCsvWriter, output_path) + finished_workers = 0 + try: + while finished_workers < CONCURRENCY: + result = await results.get() + if result is None: + finished_workers += 1 + continue + await loop.run_in_executor(executor, writer.write_result, result) + metadata, features = result + counts["查询坐标"] += 1 + status_key = {"成功": "命中坐标", "未命中": "未命中坐标"}.get(metadata["查询状态"], "失败坐标") + counts[status_key] += 1 + counts["楼宇结果行"] += len(features) + if counts["查询坐标"] == 1 or counts["查询坐标"] % PROGRESS_EVERY == 0: + print(f"已写入 {counts['查询坐标']} 个坐标,命中 {counts['命中坐标']},未命中 {counts['未命中坐标']},失败 {counts['失败坐标']}", flush=True) + finally: + await loop.run_in_executor(executor, writer.close) + + with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source: reader = csv.DictReader(source) required = {ID_COLUMN, LONGITUDE_COLUMN, LATITUDE_COLUMN} if not required.issubset(reader.fieldnames or []): raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}") selected = islice(reader, START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT) + old_signal_handler = None + if handle_signals: + old_signal_handler = signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(request_stop)) try: - for point in selected: - metadata = {"查询序号": point.get(ID_COLUMN), "查询经度": point.get(LONGITUDE_COLUMN), - "查询纬度": point.get(LATITUDE_COLUMN), "命中数量": 0, "要素ID": "", "错误信息": ""} - features = [] - try: - lon = coordinate(point.get(LONGITUDE_COLUMN), -180, 180) - lat = coordinate(point.get(LATITUDE_COLUMN), -90, 90) - features = fetch_features(opener, lon, lat) - metadata["查询状态"] = "成功" if features else "未命中" - metadata["命中数量"] = len(features) - counts["命中坐标" if features else "未命中坐标"] += 1 - except ValueError as exc: - metadata.update(查询状态="坐标无效", 错误信息=str(exc)) - counts["失败坐标"] += 1 - except QueryError as exc: - metadata.update(查询状态="请求失败", 错误信息=str(exc)) - counts["失败坐标"] += 1 - if isinstance(exc, AuthenticationError): - stop_reason = str(exc) - counts["查询坐标"] += 1 - if features: - for feature in features: - properties = feature["properties"] - for key in properties: - if key in QUERY_COLUMNS: - raise ValueError(f"properties 字段 {key} 与查询信息列重名,请调整 QUERY_COLUMNS") - if key not in property_seen: - property_seen.add(key) - property_fields.append(key) - row = {**metadata, "要素ID": feature.get("id", ""), **properties} - spool.write(json.dumps(row, ensure_ascii=False) + "\n") - counts["楼宇结果行"] += 1 - else: - spool.write(json.dumps(metadata, ensure_ascii=False) + "\n") - if counts["查询坐标"] == 1 or counts["查询坐标"] % PROGRESS_EVERY == 0 or stop_reason: - print(f"已查询 {counts['查询坐标']} 个坐标,命中 {counts['命中坐标']},未命中 {counts['未命中坐标']},失败 {counts['失败坐标']}", flush=True) - if stop_reason: - break - if REQUEST_INTERVAL: - time.sleep(REQUEST_INTERVAL) - except KeyboardInterrupt: - interrupted = True + with ThreadPoolExecutor(max_workers=1, thread_name_prefix="csv-writer") as executor: + async with aiohttp.ClientSession( + connector=aiohttp.TCPConnector(limit=CONCURRENCY, limit_per_host=CONCURRENCY), + timeout=aiohttp.ClientTimeout(total=TIMEOUT), trust_env=True, + headers={"Cookie": COOKIES.strip(), "Referer": REFERER, + "Accept": "application/json", "Accept-Encoding": "gzip", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/155.0"}, + ) as session: + tasks = [asyncio.create_task(write_results(executor))] + tasks.extend(asyncio.create_task(query_worker(session, selected)) for _ in range(CONCURRENCY)) + try: + await asyncio.gather(*tasks) + finally: + stop.set() + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) finally: - # 先收集所有 properties 字段,再流式生成统一表头,避免全量结果驻留内存。 - spool.seek(0) - with output_path.open("w", encoding=OUTPUT_ENCODING, newline="") as destination: - writer = csv.DictWriter(destination, fieldnames=QUERY_COLUMNS + property_fields) - writer.writeheader() - for line in spool: - writer.writerow({key: csv_value(value) for key, value in json.loads(line).items()}) + if old_signal_handler is not None: + signal.signal(signal.SIGINT, old_signal_handler) print(";".join(f"{key}:{value}" for key, value in counts.items())) print(f"输出:{output_path}") if interrupted: @@ -211,6 +285,10 @@ def main(): return 1 if interrupted or stop_reason or counts["失败坐标"] else 0 +def main(): + return asyncio.run(async_main()) + + if __name__ == "__main__": try: raise SystemExit(main()) diff --git a/README.md b/README.md index 6b6bf40..881ae62 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,17 @@ ## 独立楼宇批量查询 -`GetNRBuildingsData.py` 独立运行,不调用 `main.py`,只依赖 Python 标准库。 +`GetNRBuildingsData.py` 独立运行,不调用 `main.py`。先运行 `python -m pip install -r requirements-nr-buildings.txt` 安装异步请求依赖 `aiohttp`。 1. 在脚本顶部填写完整 WFS `URL`(含 `ak`、`sig` 等原参数)和 `COOKIES`。 2. 默认读取 `source/NRBuildingsPoint.csv`,使用 `序号`、`经度`、`维度` 三列,输入编码为 GBK/GB18030。 -3. 运行 `python GetNRBuildingsData.py`,默认只查询 `LIMIT = 10` 条,输出 `output/NRBuildingsData.csv`。确认结果后将 `LIMIT` 改为 `None`;`START_ROW` 可指定起始数据行。 +3. 运行 `python GetNRBuildingsData.py`,当前 `LIMIT = 1000`,输出 `output/NRBuildingsData.csv`。将 `LIMIT` 改为 `None` 可查询剩余全部;`START_ROW` 可指定起始数据行。 -脚本自动把 URL 中的 `CQL_FILTER` 替换成 `POINT(经度 纬度)` 点查询,坐标之间使用空格。输出表头包含查询坐标、状态以及所有返回 `properties` 字段;一个坐标命中多个楼宇时输出多行,未命中或失败时保留状态行。认证失败停止后续请求,按 Ctrl+C 中断会保存已完成结果。URL 和 Cookies 留空供手动填写,禁止把有效凭证提交到 Git。 +脚本自动把 URL 中的 `CQL_FILTER` 替换成 `POINT(经度 纬度)` 点查询,坐标之间使用空格。输出表头包含查询坐标、状态以及所有返回 `properties` 字段;一个坐标命中多个楼宇时输出多行,未命中或失败时保留状态行。Git 中的 URL 和 Cookies 留空,本地可填写默认值;有效凭证不得提交到 Git。 + +`CONCURRENCY = 8` 控制并发查询协程数。网络请求共用连接池,完成后进入最多缓存 `CONCURRENCY × 2` 个结果的队列。唯一的写入线程按返回顺序逐次追加 CSV 并 `flush`,因此未查完也能看到已返回的数据;用查询序号关联原坐标,输出不保证输入顺序。若后续响应新增字段,写入线程会原子替换 CSV 以扩展表头并保留已有行。 + +`REQUEST_INTERVAL` 是每个协程领取下一个坐标前的间隔。认证失败或按 Ctrl+C 时停止领取新坐标,正在处理的坐标和已入队结果会写完再退出。写文件失败会取消查询任务并报错,不会让队列永久等待。 本次取源表前 9 条及序号 `JM443411` 的坐标试跑,结果见 `output/NRBuildingsData_test10.csv`:7 条命中、3 条未命中、0 条请求失败。 diff --git a/requirements-nr-buildings.txt b/requirements-nr-buildings.txt new file mode 100644 index 0000000..94b9fc9 --- /dev/null +++ b/requirements-nr-buildings.txt @@ -0,0 +1 @@ +aiohttp==3.14.3 diff --git a/tests/test_nr_buildings.py b/tests/test_nr_buildings.py new file mode 100644 index 0000000..3dfb4af --- /dev/null +++ b/tests/test_nr_buildings.py @@ -0,0 +1,157 @@ +import asyncio +import csv +from pathlib import Path +import re +import signal +import tempfile +import threading +import unittest +from unittest.mock import patch + +from aiohttp import web +from aiohttp.test_utils import TestServer + +import GetNRBuildingsData as script + + +class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.input = Path(self.directory.name) / "points.csv" + self.output = Path(self.directory.name) / "results.csv" + with self.input.open("w", encoding="utf-8-sig", newline="") as destination: + writer = csv.writer(destination) + writer.writerow(["序号", "经度", "维度"]) + writer.writerows([[str(i), str(i), "22"] for i in range(6)]) + settings = patch.multiple(script, INPUT_CSV=self.input, OUTPUT_CSV=self.output, + INPUT_ENCODING="utf-8-sig", URL="http://127.0.0.1/wfs", COOKIES="test-session", + START_ROW=1, LIMIT=6, CONCURRENCY=3, REQUEST_INTERVAL=0, MAX_RETRIES=0) + settings.start() + self.addCleanup(settings.stop) + + def read_rows(self): + with self.output.open(encoding="utf-8-sig", newline="") as source: + reader = csv.DictReader(source) + return reader.fieldnames, list(reader) + + async def test_bounded_concurrency_and_live_single_thread_writes(self): + gate = asyncio.Event() + wrote_early = asyncio.Event() + active, maximum = 0, 0 + loop = asyncio.get_running_loop() + writer_threads = set() + real_write = script.StreamingCsvWriter.write_result + + def record_write(writer, result): + writer_threads.add(threading.get_ident()) + real_write(writer, result) + loop.call_soon_threadsafe(wrote_early.set) + + async def handler(request): + nonlocal active, maximum + identifier = int(re.search(r"POINT\((\d+) 22\)", request.query["CQL_FILTER"]).group(1)) + active += 1 + maximum = max(maximum, active) + try: + if identifier == 0: + await gate.wait() + else: + await asyncio.sleep(0.01 * identifier) + properties = {"building_id": f"building-{identifier}", "metric": identifier} + if identifier == 0: + properties["late_field"] = "last response" + features = [{"id": str(identifier), "properties": properties}] + if identifier == 1: + features = [] + if identifier == 2: + features.append({"id": "second", "properties": {"building_id": "second", "extra": [1, 2]}}) + return web.json_response({"type": "FeatureCollection", "features": features, "numberMatched": len(features)}) + finally: + active -= 1 + + app = web.Application() + app.router.add_get("/wfs", handler) + async with TestServer(app) as server: + with patch.object(script, "URL", str(server.make_url("/wfs"))), \ + patch.object(script.StreamingCsvWriter, "write_result", record_write): + task = asyncio.create_task(script.async_main(handle_signals=False)) + try: + await asyncio.wait_for(wrote_early.wait(), 5) + _, early = self.read_rows() + self.assertTrue(early) + self.assertNotIn("0", [row["查询序号"] for row in early]) + self.assertFalse(task.done()) + finally: + gate.set() + self.assertEqual(await asyncio.wait_for(task, 5), 0) + headers, rows = self.read_rows() + self.assertGreaterEqual(maximum, 2) + self.assertLessEqual(maximum, 3) + self.assertEqual(len(writer_threads), 1) + self.assertNotIn(threading.get_ident(), writer_threads) + self.assertEqual(len(rows), 7) + self.assertEqual({row["查询序号"] for row in rows}, {str(i) for i in range(6)}) + self.assertIn("late_field", headers) + self.assertIn("extra", headers) + self.assertTrue(all(None not in row for row in rows)) + self.assertEqual(next(row for row in rows if row["查询序号"] == "0")["late_field"], "last response") + self.assertEqual(next(row for row in rows if row["查询序号"] == "1")["查询状态"], "未命中") + self.assertEqual(len([row for row in rows if row["查询序号"] == "2"]), 2) + self.assertEqual(list(Path(self.directory.name).glob("*.tmp")), []) + + async def test_writer_failure_cancels_workers_without_queue_deadlock(self): + async def immediate(*args): + return [{"id": "id", "properties": {"building_id": "test"}}] + + with patch.object(script, "fetch_features", immediate), \ + patch.object(script.StreamingCsvWriter, "write_result", side_effect=OSError("write failed")): + with self.assertRaisesRegex(OSError, "write failed"): + await asyncio.wait_for(script.async_main(handle_signals=False), 5) + + async def test_authentication_failure_stops_taking_new_points(self): + calls = 0 + + async def unauthorized(*args): + nonlocal calls + calls += 1 + await asyncio.sleep(0.01) + raise script.AuthenticationError("expired") + + with patch.object(script, "fetch_features", unauthorized): + self.assertEqual(await asyncio.wait_for(script.async_main(handle_signals=False), 5), 1) + _, rows = self.read_rows() + self.assertLessEqual(calls, script.CONCURRENCY) + self.assertEqual(len(rows), calls) + self.assertTrue(all(row["查询状态"] == "请求失败" for row in rows)) + + async def test_interrupt_finishes_inflight_results_before_closing_writer(self): + started = asyncio.Event() + release = asyncio.Event() + calls = 0 + + async def slow(*args): + nonlocal calls + calls += 1 + if calls == script.CONCURRENCY: + started.set() + await release.wait() + return [{"id": "id", "properties": {"building_id": "test"}}] + + with patch.object(script, "fetch_features", slow): + task = asyncio.create_task(script.async_main()) + try: + await asyncio.wait_for(started.wait(), 5) + signal.raise_signal(signal.SIGINT) + await asyncio.sleep(0) + finally: + release.set() + self.assertEqual(await asyncio.wait_for(task, 5), 1) + _, rows = self.read_rows() + self.assertEqual(calls, script.CONCURRENCY) + self.assertEqual(len(rows), calls) + self.assertTrue(all(row["查询状态"] == "成功" for row in rows)) + + +if __name__ == "__main__": + unittest.main()