68 lines
2.9 KiB
Python
68 lines
2.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import secrets
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def _app_dir() -> Path:
|
|
"""定位 .env / 数据所在目录。
|
|
|
|
- 源码运行:fileserver/core/config.py → fileserver/
|
|
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
|
"""
|
|
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
|
return Path(sys.executable).resolve().parent
|
|
return Path(__file__).resolve().parent.parent
|
|
|
|
|
|
APP_DIR = _app_dir()
|
|
|
|
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
|
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
|
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
|
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
|
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
|
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
|
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
|
|
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
|
|
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
|
|
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
|
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
|
# 心跳上报间隔(秒)
|
|
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
|
|
|
|
|
def load_dotenv() -> None:
|
|
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
|
env_path = APP_DIR / ".env"
|
|
if not env_path.is_file():
|
|
return
|
|
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
|
_line = _ln.strip()
|
|
if not _line or _line.startswith("#") or "=" not in _line:
|
|
continue
|
|
_k, _v = _line.split("=", 1)
|
|
k = _k.strip()
|
|
if k and k not in os.environ:
|
|
os.environ[k] = _v.strip()
|
|
|
|
|
|
load_dotenv()
|
|
|
|
# load_dotenv 后再取一次,保证 .env 值生效
|
|
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
|
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
|
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
|
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
|
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
|
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
|
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
|
|
|
|
|
def default_token() -> str:
|
|
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
|
return TOKEN or secrets.token_urlsafe(24) |