Files
MarketGrid/ui/building_page.py
T

80 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import streamlit as st
from toolbox.tasks import ROOT, start_task
from .inputs import file_input
from .task_panel import show_started, task_panel
# 上次填写的服务地址/登录信息保存在本地 output 目录(已被 .gitignore 忽略),下次自动读取。
CONNECTION_FILE = ROOT / "output" / "toolbox" / "nr_connection.json"
CONNECTION_KEYS = ("URL", "COOKIES", "REFERER")
def script_defaults():
import GetNRBuildingsData as script
return {key: str(getattr(script, key, "") or "") for key in CONNECTION_KEYS}
def load_connection():
"""优先本地保存值,没有则显示脚本内默认值。"""
defaults = script_defaults()
try:
data = json.loads(CONNECTION_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError):
return defaults
return {key: str(data.get(key, "") or "") or defaults[key] for key in CONNECTION_KEYS}
def save_connection(values):
if values is None:
CONNECTION_FILE.unlink(missing_ok=True)
return
CONNECTION_FILE.parent.mkdir(parents=True, exist_ok=True)
CONNECTION_FILE.write_text(json.dumps(values, ensure_ascii=False, indent=2), encoding="utf-8")
def connection_input(label, key, placeholder=None):
"""type=search 的输入框在框内右侧自带 ✕ 清除按钮(样式见 layout.py)。"""
return st.text_input(label, key=f"conn_{key}", placeholder=placeholder, type="search")
def render():
st.markdown("## 楼宇数据查询")
st.caption("按楼宇轮廓(WKT)查询:先计算落在轮廓内部的点,再按该点查询。")
source = file_input("楼宇轮廓清单", "source/NRBuildPolygon.csv", "csv", "building_csv")
if "conn_URL" not in st.session_state:
for key, value in load_connection().items():
st.session_state[f"conn_{key}"] = value
st.markdown("**连接信息**(默认显示脚本内配置或上次保存值;修改后保存到本地,下次自动读取)")
url = connection_input("服务地址", "URL", "https://...wfs?...ak=...&sig=...")
cookies = connection_input("登录信息(Cookies)", "COOKIES", "CASTGC=...")
referer = connection_input("来源页(可留空)", "REFERER", "可留空")
with st.form("building_run"):
c1, c2, c3 = st.columns(3)
start = c1.number_input("起始行", 1, value=1)
limit = c2.number_input("查询数量(0 表示全部)", 0, value=1000)
concurrency = c3.number_input("并发数", 1, 32, 8)
encoding = st.selectbox("文件编码(按内容自动识别,识别不出时按此项)", ["gbk", "utf-8-sig"])
with st.expander("高级参数"):
timeout = st.number_input("超时(秒)", 1, 300, 30)
retries = st.number_input("失败重试", 0, 10, 2)
interval = st.number_input("请求间隔(秒)", 0.0, 60.0, 0.2, 0.1)
submitted = st.form_submit_button("开始查询", type="primary")
if submitted:
try:
if not source:
raise ValueError("请先导入楼宇轮廓文件。")
url, cookies, referer = url.strip(), cookies.strip(), referer.strip()
override = bool(url or cookies)
if override and (not url.startswith(("http://", "https://")) or not cookies):
raise ValueError("服务地址和登录信息需同时填写,且地址以 http(s):// 开头。")
params = {"INPUT_CSV": source, "INPUT_ENCODING": encoding, "START_ROW": start,
"LIMIT": limit or None, "CONCURRENCY": concurrency, "TIMEOUT": timeout,
"MAX_RETRIES": retries, "REQUEST_INTERVAL": interval}
credentials = {"URL": url, "COOKIES": cookies, "REFERER": referer} if override else None
save_connection(credentials)
show_started(start_task("buildings", params, credentials))
except (OSError, ValueError, UnicodeError) as error:
st.error(str(error))
if st.session_state.get("last_task"):
task_panel(st.session_state["last_task"])