feat: 实现已确认的登录、采集和任务导出
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
"""把表格读成小区多期记录,并按选择的格式写出。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
import xlwt
|
||||
|
||||
CELL_HEADERS = ("小区", "cell_key", "cell")
|
||||
TIME_HEADERS = ("时间", "observed_at", "time")
|
||||
|
||||
|
||||
def decode_text(content: bytes) -> str:
|
||||
for encoding in ("utf-8-sig", "gbk"):
|
||||
try:
|
||||
return content.decode(encoding)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return content.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def _parse_time(value: str) -> datetime:
|
||||
text = value.strip()
|
||||
if not text:
|
||||
raise ValueError("缺少时间")
|
||||
normalized = text.replace("/", "-").replace("T", " ")
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||
try:
|
||||
parsed = datetime.strptime(normalized, fmt)
|
||||
return parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError("时间格式无法识别")
|
||||
|
||||
|
||||
def rows_from_table(headers: list[str], records: list[list[str]]) -> list[dict]:
|
||||
cell_index = next((index for index, name in enumerate(headers) if name.strip() in CELL_HEADERS), None)
|
||||
time_index = next((index for index, name in enumerate(headers) if name.strip() in TIME_HEADERS), None)
|
||||
if cell_index is None or time_index is None:
|
||||
raise ValueError("表格需要包含小区和时间")
|
||||
parsed: list[dict] = []
|
||||
for record in records:
|
||||
if cell_index >= len(record) or not str(record[cell_index]).strip():
|
||||
continue
|
||||
metrics = {}
|
||||
for index, name in enumerate(headers):
|
||||
if index in {cell_index, time_index} or not name.strip():
|
||||
continue
|
||||
metrics[name.strip()] = "" if index >= len(record) else str(record[index]).strip()
|
||||
parsed.append(
|
||||
{
|
||||
"cell_key": str(record[cell_index]).strip(),
|
||||
"observed_at": _parse_time(str(record[time_index]) if time_index < len(record) else ""),
|
||||
"metrics": metrics,
|
||||
}
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_csv(content: bytes) -> list[dict]:
|
||||
reader = csv.reader(io.StringIO(decode_text(content)))
|
||||
rows = list(reader)
|
||||
if not rows:
|
||||
return []
|
||||
return rows_from_table(rows[0], rows[1:])
|
||||
|
||||
|
||||
def parse_xlsx(content: bytes) -> list[dict]:
|
||||
book = load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||
sheet = book.active
|
||||
rows = [["" if cell is None else str(cell) for cell in row] for row in sheet.iter_rows(values_only=True)]
|
||||
book.close()
|
||||
if not rows:
|
||||
return []
|
||||
return rows_from_table(rows[0], rows[1:])
|
||||
|
||||
|
||||
def parse_upload(name: str, content: bytes) -> list[dict]:
|
||||
lowered = name.lower()
|
||||
if lowered.endswith(".xlsx"):
|
||||
return parse_xlsx(content)
|
||||
return parse_csv(content)
|
||||
|
||||
|
||||
def _flat_rows(rows: list[dict]) -> tuple[list[str], list[list[str]]]:
|
||||
metric_names: list[str] = []
|
||||
for row in rows:
|
||||
for key in row["metrics"]:
|
||||
if key not in metric_names:
|
||||
metric_names.append(key)
|
||||
headers = ["小区", "时间", *metric_names]
|
||||
body = []
|
||||
for row in rows:
|
||||
moment = row["observed_at"]
|
||||
if isinstance(moment, datetime):
|
||||
text = moment.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
||||
else:
|
||||
text = str(moment)
|
||||
body.append([row["cell_key"], text, *[str(row["metrics"].get(name, "")) for name in metric_names]])
|
||||
return headers, body
|
||||
|
||||
|
||||
def write_csv(rows: list[dict]) -> bytes:
|
||||
headers, body = _flat_rows(rows)
|
||||
buffer = io.StringIO()
|
||||
writer = csv.writer(buffer)
|
||||
writer.writerow(headers)
|
||||
writer.writerows(body)
|
||||
return buffer.getvalue().encode("utf-8-sig")
|
||||
|
||||
|
||||
def write_xlsx(rows: list[dict]) -> bytes:
|
||||
headers, body = _flat_rows(rows)
|
||||
book = Workbook()
|
||||
sheet = book.active
|
||||
sheet.append(headers)
|
||||
for line in body:
|
||||
sheet.append(line)
|
||||
buffer = io.BytesIO()
|
||||
book.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_xls(rows: list[dict]) -> bytes:
|
||||
headers, body = _flat_rows(rows)
|
||||
book = xlwt.Workbook()
|
||||
sheet = book.add_sheet("结果")
|
||||
for column, name in enumerate(headers):
|
||||
sheet.write(0, column, name)
|
||||
for row_index, line in enumerate(body, start=1):
|
||||
for column, value in enumerate(line):
|
||||
sheet.write(row_index, column, value)
|
||||
buffer = io.BytesIO()
|
||||
book.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_table(file_format: str, rows: list[dict]) -> tuple[str, bytes]:
|
||||
if file_format == "xlsx":
|
||||
return "result.xlsx", write_xlsx(rows)
|
||||
if file_format == "xls":
|
||||
return "result.xls", write_xls(rows)
|
||||
if file_format == "csv":
|
||||
return "result.csv", write_csv(rows)
|
||||
raise ValueError("结果文件只能是 xlsx、xls 或 csv")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""从 FTP/SFTP 或已登录的大数据平台取回表格。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from ftplib import FTP
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import paramiko
|
||||
|
||||
from app.nqi.client import NqiClient
|
||||
|
||||
|
||||
def fetch_ftp(config: dict) -> tuple[str, bytes]:
|
||||
protocol = str(config.get("protocol") or "sftp")
|
||||
host = str(config.get("host") or "")
|
||||
path = str(config.get("path") or "")
|
||||
username = str(config.get("username") or "")
|
||||
password = str(config.get("password") or "")
|
||||
port = int(config.get("port") or (21 if protocol == "ftp" else 22))
|
||||
if not host or not path:
|
||||
raise ValueError("请填写主机和路径")
|
||||
if protocol == "ftp":
|
||||
ftp = FTP()
|
||||
ftp.connect(host, port, timeout=30)
|
||||
ftp.login(username, password)
|
||||
buffer = io.BytesIO()
|
||||
ftp.retrbinary(f"RETR {path}", buffer.write)
|
||||
ftp.quit()
|
||||
return path.rsplit("/", 1)[-1], buffer.getvalue()
|
||||
transport = paramiko.Transport((host, port))
|
||||
transport.connect(username=username, password=password)
|
||||
sftp = paramiko.SFTPClient.from_transport(transport)
|
||||
if sftp is None:
|
||||
transport.close()
|
||||
raise ValueError("无法连接 SFTP")
|
||||
buffer = io.BytesIO()
|
||||
sftp.getfo(path, buffer)
|
||||
sftp.close()
|
||||
transport.close()
|
||||
return path.rsplit("/", 1)[-1], buffer.getvalue()
|
||||
|
||||
|
||||
async def fetch_nqi(client: NqiClient, config: dict) -> tuple[str, bytes]:
|
||||
address = str(config.get("url") or "").strip()
|
||||
if not address:
|
||||
raise ValueError("未配置 NQI 采集地址")
|
||||
parsed = urlparse(address)
|
||||
if parsed.scheme not in {"http", "https"}:
|
||||
raise ValueError("NQI 采集地址需要是 http 或 https")
|
||||
return await client.fetch_bytes(address)
|
||||
Reference in New Issue
Block a user