文件
workbuddy-portal/workbuddy_portal/__init__.py
T
wangchuanli 23799b4ea5 feat(oss): 补齐开源声明体系(MIT + 第三方声明 + 贡献/安全/行为准则)
* LICENSE              —— MIT
  * THIRD-PARTY-NOTICES  —— 依赖清单、再分发合规说明(含随仓库分发的
                            Apache ECharts 5.6.0 / Apache-2.0)与自查清单
  * CONTRIBUTING.md      —— 开发环境、五层验证、必须遵守的不变量、提交规范
  * SECURITY.md          —— 漏洞私有报告渠道、已有措施、已知非目标
  * CODE_OF_CONDUCT.md   —— 改编自 Contributor Covenant 2.1
  * .github/             —— Bug 报告 / 功能建议表单 + PR 模板
  * .editorconfig        —— 与 .gitattributes 保持一致
  * 全部 Python / Shell 源文件加 SPDX-License-Identifier: MIT 头
  * README 增加「开源与许可」章节与许可标识
2026-09-14 16:15:26 +08:00

127 行
4.7 KiB
Python
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Wang Chuanli
"""WorkBuddy Portal —— 独立 Flask 项目。
一个程序管全部:
* 采集:进程内调度线程按配置的时刻调用云端接口,增量写入 SQLite
* 存储:SQLite 单文件正本(WAL),去重靠主键,聚合下推 SQL
* 呈现:Jinja 负责配置/任务/日志/明细;ECharts 大屏独立成页,数据走 /api/*
* 鉴权:局域网可访问 ⇒ 必须有登录,cookie 等凭证存数据库由后台页面维护
用法:
python manage.py init 初始化数据库(建表 + 默认配置 + 管理员)
python manage.py serve 启动 Web(默认 0.0.0.0:8848,含调度线程)
python manage.py collect 执行一次增量采集(CLI,不影响 Web)
...
"""
import logging
import os
from datetime import timedelta
from logging.handlers import RotatingFileHandler
from flask import Flask, jsonify, render_template, request
from . import config, db, security
__version__ = "1.1.0"
PROJECT_NAME = config.PROJECT_NAME
def _setup_logging(app):
config.ensure_dirs()
handler = RotatingFileHandler(config.APP_LOG, maxBytes=2 * 1024 * 1024,
backupCount=3, encoding="utf-8")
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s [%(name)s] %(message)s"))
handler.setLevel(logging.INFO)
root = logging.getLogger()
if not any(isinstance(h, RotatingFileHandler) and getattr(h, "baseFilename", "") == handler.baseFilename
for h in root.handlers):
root.addHandler(handler)
root.setLevel(logging.INFO)
app.logger.info("启动 %s v%s(db=%s)", __name__, __version__, config.SQLITE_PATH)
def create_app(start_scheduler=True, do_init_db=True, **overrides):
app = Flask(__name__,
template_folder="web/templates",
static_folder="web/static",
static_url_path="/static")
app.config.update(
SECRET_KEY=config.secret_key(),
PERMANENT_SESSION_LIFETIME=timedelta(hours=config.SESSION_HOURS),
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_NAME="workbuddy_portal_sid",
MAX_CONTENT_LENGTH=4 * 1024 * 1024,
TEMPLATES_AUTO_RELOAD=True,
SEND_FILE_MAX_AGE_DEFAULT=0,
)
app.config.update(overrides)
app.json.ensure_ascii = False
app.json.sort_keys = False
if do_init_db:
db.init_db()
_setup_logging(app)
security.init_app(app)
from .web import register as register_web
register_web(app)
@app.teardown_appcontext
def _close(exc=None):
db.close_db(exc)
# ---- 错误处理 ----
@app.errorhandler(404)
def _404(e):
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "not_found", "message": "接口不存在"}), 404
return render_template("error.html", code=404, message="页面不存在"), 404
@app.errorhandler(400)
def _400(e):
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "bad_request", "message": str(e)}), 400
return render_template("error.html", code=400, message=str(e)), 400
@app.errorhandler(403)
def _403(e):
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "forbidden", "message": "没有权限"}), 403
return render_template("error.html", code=403, message="没有权限"), 403
@app.errorhandler(500)
def _500(e):
app.logger.exception("内部错误")
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "internal", "message": "服务器内部错误"}), 500
return render_template("error.html", code=500, message="服务器内部错误"), 500
@app.errorhandler(ValueError)
def _value_error(e):
"""参数解析类异常统一归 400(例如 base64/日期/整数解析失败)。
没有这层的话,一个手写的 query string 就能把 500 页面暴露出去。
"""
app.logger.warning("参数错误:%s", e)
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "bad_request", "message": str(e)}), 400
return render_template("error.html", code=400, message=str(e)), 400
@app.context_processor
def _inject():
return {"app_version": __version__, "nav_active": "",
"project_name": config.PROJECT_NAME,
"project_title": config.PROJECT_TITLE,
"project_desc": config.PROJECT_DESC}
if start_scheduler:
from . import scheduler
scheduler.start_from_app(app)
return app