#!/usr/bin/env python3
"""
Hugging Face Spaces WordPress 应用入口文件
这个文件是 Hugging Face Spaces 的标准入口点,
但实际的 WordPress 应用运行在 Docker 容器中。
该文件主要用于:
1. 提供应用信息
2. 健康检查
3. 重定向到 WordPress
"""
import os
import time
import subprocess
from flask import Flask, redirect, jsonify, render_template_string
app = Flask(__name__)
# 应用信息
APP_INFO = {
"name": "WordPress for Hugging Face Spaces",
"version": "1.0.0",
"description": "WordPress 单容器部署,使用 SQLite 数据库,包含自动清理功能",
"author": "Hugging Face Spaces WordPress Team",
"wordpress_url": "http://localhost:7860"
}
# HTML 模板
INDEX_TEMPLATE = """
{{ app_info.name }}
{{ app_info.name }}
版本 {{ app_info.version }}
{{ app_info.description }}
主要特性:
- 单容器 Docker 部署
- SQLite 轻量级数据库
- 自动文件清理 (保留1年)
- 性能优化配置
- 安全防护机制
- 实时监控面板
进入 WordPress
系统状态
状态: WordPress 正在运行中...
如果这是首次访问,WordPress 可能需要几分钟来初始化
"""
@app.route('/')
def index():
"""主页 - 显示应用信息"""
return render_template_string(INDEX_TEMPLATE, app_info=APP_INFO)
@app.route('/wordpress')
def wordpress():
"""重定向到 WordPress"""
return redirect('http://localhost:7860', code=302)
@app.route('/health')
def health():
"""健康检查端点"""
try:
# 检查 WordPress 容器是否运行
result = subprocess.run(
['curl', '-f', '-s', 'http://localhost:7860'],
capture_output=True,
timeout=5
)
wordpress_status = "running" if result.returncode == 0 else "stopped"
# 获取系统信息
disk_usage = subprocess.run(
['df', '-h', '/'],
capture_output=True,
text=True
).stdout.split('\n')[1].split()[4] if subprocess.run(['df', '-h', '/'], capture_output=True).returncode == 0 else "unknown"
return jsonify({
"status": "healthy",
"timestamp": time.time(),
"services": {
"wordpress": wordpress_status,
"database": "sqlite",
"cleanup": "enabled"
},
"system": {
"disk_usage": disk_usage,
"uptime": time.time()
},
"app_info": APP_INFO
})
except Exception as e:
return jsonify({
"status": "error",
"error": str(e),
"timestamp": time.time()
}), 500
@app.route('/api/info')
def api_info():
"""API 信息端点"""
return jsonify(APP_INFO)
@app.route('/api/cleanup/status')
def cleanup_status():
"""清理状态 API"""
try:
# 读取清理日志
log_file = '/var/log/wordpress/cleanup.log'
if os.path.exists(log_file):
with open(log_file, 'r') as f:
lines = f.readlines()
recent_logs = lines[-10:] if len(lines) > 10 else lines
else:
recent_logs = ["暂无清理记录"]
return jsonify({
"status": "success",
"cleanup_enabled": True,
"retention_days": 365,
"recent_logs": [line.strip() for line in recent_logs],
"log_file": log_file
})
except Exception as e:
return jsonify({
"status": "error",
"error": str(e)
}), 500
if __name__ == '__main__':
# 在 Hugging Face Spaces 中,应用应该监听端口 7860
port = int(os.environ.get('PORT', 7860))
print(f"启动 {APP_INFO['name']} v{APP_INFO['version']}")
print(f"监听端口: {port}")
print(f"WordPress URL: {APP_INFO['wordpress_url']}")
app.run(
host='0.0.0.0',
port=port,
debug=False
)