惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
C
Check Point Blog
Vercel News
Vercel News
Y
Y Combinator Blog
G
Google Developers Blog
P
Proofpoint News Feed
WordPress大学
WordPress大学
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
L
LangChain Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
博客园_首页
B
Blog RSS Feed
The Cloudflare Blog
MyScale Blog
MyScale Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Security Blog
Microsoft Security Blog

又见苍岚

COLMAP PatchMatch Stereo 算法详解 事件驱动的状态机框架:从理论到工程实践 Git 在国内网络环境下无法 Push 的排查与修复 —— 配置 Clash 代理 分段五次多项式插值原理详解 路径插值方法深度对比研究 Claude Code 使用指南 OpenClaw 记忆管理与技能创建指南 CBS(Conflict-Based Search)算法详解 A* 算法及其变种详解 OpenClaw 配置多 Agents Windows Powershell 无法加载文件,因为在此系统上禁止运行脚本问题的解决方案 MaxClaw 安装流程 大模型 AI 名词介绍 AList 网盘聚合工具简介 Protobuf 简介与测试 Claude Code 简介以及 GLM 4.7 模型接入 Github 歌词下载工具 163MusicLyrics Python __getattr__ 懒加载 Python TypedDict 机器人仿真平台 Gazebo 安装记录 机器人仿真平台 Gazebo 简介 多机器人路径规划问题(Multi-Agent Path Finding, MAPF)简介 Python exifread 读取修改过的 jpeg 信息错误问题修复 3D 坐标系变换的理解 3D 旋转矩阵基本概念 MongoDB Compass 介绍 Python 环境管理工具 uv Flutter 开发指南 Snipaste 安装下载与黑屏问题解决方案 全局路径规划算法记录
Python 实现 Web 日志查看服务
Yiwei Zhang · 2025-04-09 · via 又见苍岚
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from flask import Flask, render_template, abort, request
import os
from config import LOG_ROOT, ALLOWED_EXTENSIONS, MAX_LINES_PER_PAGE
import vvdutils as vv
import pathlib

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 10 # 静态文件缓存10s

def is_safe_path(path):
"""增强路径安全检查"""
target = os.path.abspath(os.path.join(LOG_ROOT, path))
return os.path.commonpath([LOG_ROOT, target]) == LOG_ROOT

@app.route('/')
def index():
return browse('')

@app.route('/browse/<path:subpath>')
def browse(subpath):
if not is_safe_path(subpath):
abort(403)

abs_path = os.path.join(LOG_ROOT, subpath)
if not os.path.exists(abs_path):
abort(404)

entries = []
try:
for entry in sorted(os.listdir(abs_path), key=lambda x: (not os.path.isdir(os.path.join(abs_path, x)), x.lower())):
entry_path = os.path.join(subpath, entry)
full_path = os.path.join(abs_path, entry)
# 最后修改时间(所有系统通用)

if os.path.isdir(full_path):
time_info = vv.get_file_time(full_path, datetime_res=True)
entries.append({
'name': entry,
'path': entry_path,
'is_dir': True,
'size': '-',
'modify_time': vv.time_string(datetime_obj=time_info['modify_time']),
'created_time': vv.time_string(datetime_obj=time_info['create_time'])
})
else:
ext = pathlib.Path(entry).suffix[1:].lower()
if ext not in ALLOWED_EXTENSIONS:
continue
time_info = vv.get_file_time(full_path, datetime_res=True)
entries.append({
'name': entry,
'path': entry_path,
'is_dir': False,
'size': os.path.getsize(full_path),
'modify_time': vv.time_string(datetime_obj=time_info['modify_time']),
'created_time': vv.time_string(datetime_obj=time_info['create_time'])
})
except PermissionError:
abort(403)

parent = os.path.dirname(subpath)
return render_template('browse.html',
entries=entries,
current_path=subpath,
parent=parent)

# @lru_cache(maxsize=100) # 由于时刻在变化,不能缓存
def get_cached_line_count(filepath):
return vv.get_file_line_number(filepath)

@app.route('/view/<path:filepath>')
def view_file(filepath):
if not is_safe_path(filepath):
abort(403)

page = request.args.get('page', 1, type=int)
search_term = request.args.get('search', '').lower()
abs_path = os.path.join(LOG_ROOT, filepath)

if not os.path.isfile(abs_path):
abort(404)

try:
total_lines = get_cached_line_count(abs_path)
except Exception as e:
app.logger.error(f"读取文件行数失败: {str(e)}")
abort(500)

total_pages = max(1, (total_lines + MAX_LINES_PER_PAGE - 1) // MAX_LINES_PER_PAGE)
page = max(1, min(page, total_pages))

try:
with open(abs_path, 'r', encoding='utf-8', errors='ignore') as f:
start_line = (page - 1) * MAX_LINES_PER_PAGE
content = []
for _ in range(start_line):
if not f.readline():
break
for _ in range(MAX_LINES_PER_PAGE):
line = f.readline()
if not line:
break
if search_term in line.lower():
content.append(line)
except IOError as e:
app.logger.error(f"文件读取失败: {str(e)}")
abort(500)

return render_template('view.html',
filename=os.path.basename(filepath),
content=''.join(content),
filepath=filepath,
page=page,
total_pages=total_pages)

@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404

@app.errorhandler(403)
def forbidden(e):
return render_template('403.html'), 403

if __name__ == '__main__':
app.run(debug=True)