52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
"""从 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)
|