feat: 异步查询楼宇并实时单线程写入CSV
This commit is contained in:
+166
-88
@@ -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())
|
||||
|
||||
Reference in New Issue
Block a user