Skip to content

Commit 755294b

Browse files
author
cloudQuant
committed
fix cards
1 parent 3e350dd commit 755294b

26 files changed

Lines changed: 1793 additions & 298 deletions

deep_fix.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""
2+
深度修复 WoniuNote 中的所有控制器文件,解决视图函数返回整数的问题
3+
"""
4+
5+
import os
6+
import re
7+
import sys
8+
9+
def find_and_fix_integer_returns(directory):
10+
"""在所有控制器文件中查找并修复直接返回整数的问题"""
11+
controller_dir = os.path.join(directory, 'woniunote', 'controller')
12+
fixed_files = []
13+
patterns = [
14+
r'(\s+)return\s+(\d+)(\s*$|\s*#.*$)', # 直接返回数字
15+
r'(\s+)return\s+(id|card_id|item_id|article_id|user_id|[\w_]+_id)(\s*$|\s*#.*$)', # 返回ID变量
16+
]
17+
18+
print("开始深度检查并修复所有控制器文件...")
19+
20+
for root, _, files in os.walk(controller_dir):
21+
for filename in files:
22+
if filename.endswith('.py'):
23+
file_path = os.path.join(root, filename)
24+
file_content = None
25+
26+
with open(file_path, 'r', encoding='utf-8') as f:
27+
file_content = f.read()
28+
29+
modified = False
30+
31+
# 模式1: 直接返回数字
32+
for pattern in patterns:
33+
def replace_func(match):
34+
nonlocal modified
35+
indent = match.group(1)
36+
value = match.group(2)
37+
comment = match.group(3) if len(match.groups()) > 2 else ''
38+
modified = True
39+
return f"{indent}return render_template('error-404.html'), 404{comment}"
40+
41+
new_content, count = re.subn(pattern, replace_func, file_content)
42+
if count > 0:
43+
file_content = new_content
44+
print(f" 在 {filename} 中找到并修复了 {count} 处返回整数的问题")
45+
46+
# 模式2: 检查 before_request 钩子
47+
before_hook_pattern = r'(@\w+\.before_request\s*\n\s*def\s+\w+\([^)]*\):.*?)(return\s+["\'].*?["\'])'
48+
new_content, count = re.subn(
49+
before_hook_pattern,
50+
r'\1return jsonify({"error": "forbidden"}), 403',
51+
file_content,
52+
flags=re.DOTALL
53+
)
54+
if count > 0:
55+
file_content = new_content
56+
modified = True
57+
print(f" 在 {filename} 中找到并修复了 {count} 处 before_request 钩子返回值问题")
58+
59+
# 模式3: 检查可能返回None的函数
60+
none_return_pattern = r'(def\s+\w+\([^)]*\):.*?)(\s+return\s+None)'
61+
new_content, count = re.subn(
62+
none_return_pattern,
63+
r'\1\2 if request.method == "GET" else jsonify({"status": "ok"})',
64+
file_content,
65+
flags=re.DOTALL
66+
)
67+
if count > 0:
68+
file_content = new_content
69+
modified = True
70+
print(f" 在 {filename} 中找到并修复了 {count} 处可能返回None的问题")
71+
72+
if modified:
73+
with open(file_path, 'w', encoding='utf-8') as f:
74+
f.write(file_content)
75+
fixed_files.append(filename)
76+
77+
if fixed_files:
78+
print(f"\n成功修复了以下 {len(fixed_files)} 个文件:")
79+
for file in fixed_files:
80+
print(f" - {file}")
81+
else:
82+
print("\n未发现需要修复的控制器文件。")
83+
84+
# 特殊处理: 检查app.py中所有路由定义
85+
app_path = os.path.join(directory, 'woniunote', 'app.py')
86+
if os.path.exists(app_path):
87+
print("\n正在检查主应用文件 app.py...")
88+
with open(app_path, 'r', encoding='utf-8') as f:
89+
app_content = f.read()
90+
91+
# 查找所有路由函数
92+
route_pattern = r'(@app\.route\([^)]+\)\s*\n\s*def\s+\w+\([^)]*\):\s*.*?)(return\s+\d+)'
93+
new_content, count = re.subn(
94+
route_pattern,
95+
r'\1return render_template("error-404.html"), 404',
96+
app_content,
97+
flags=re.DOTALL
98+
)
99+
if count > 0:
100+
with open(app_path, 'w', encoding='utf-8') as f:
101+
f.write(new_content)
102+
print(f" 在 app.py 中修复了 {count} 处路由函数返回问题")
103+
else:
104+
print(" app.py 中未发现需要修复的路由函数。")
105+
106+
if __name__ == "__main__":
107+
project_dir = os.path.dirname(os.path.abspath(__file__))
108+
find_and_fix_integer_returns(project_dir)
109+
print("\n修复完成! 请重启Flask应用以应用更改。")

direct_reset_tables.py

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""
4+
直接使用SQL语句重置Card和Todo模块的数据库表,避开循环导入和模型重复定义问题
5+
"""
6+
import os
7+
import sys
8+
import datetime
9+
import pymysql
10+
import yaml
11+
12+
# 直接读取配置文件,避免导入应用模块
13+
def direct_read_config():
14+
"""直接从配置文件读取数据库信息,避免导入应用模块"""
15+
config_path = os.path.join('woniunote', 'configs', 'config.py')
16+
try:
17+
# 读取Python配置文件内容
18+
config_content = {}
19+
with open(config_path, 'r', encoding='utf-8') as f:
20+
# 提取数据库连接字符串
21+
for line in f:
22+
if 'SQLALCHEMY_DATABASE_URI' in line:
23+
# 提取引号内的内容
24+
import re
25+
match = re.search(r'["\'](.+?)["\']', line)
26+
if match:
27+
db_uri = match.group(1)
28+
return {'database': {'SQLALCHEMY_DATABASE_URI': db_uri}}
29+
30+
# 如果没有找到连接字符串,返回None
31+
print("在配置文件中未找到数据库连接字符串")
32+
return None
33+
except Exception as e:
34+
print(f"读取配置文件出错: {str(e)}")
35+
return None
36+
37+
# 解析数据库URI
38+
def direct_parse_db_uri(uri):
39+
"""解析数据库URI获取连接信息"""
40+
# mysql://username:password@host:port/database
41+
if not uri.startswith('mysql://'):
42+
raise ValueError("仅支持MySQL数据库")
43+
44+
# 去除协议前缀
45+
uri = uri.replace('mysql://', '')
46+
47+
# 提取用户名和密码
48+
auth, rest = uri.split('@', 1)
49+
user, password = auth.split(':', 1)
50+
51+
# 提取主机、端口和数据库名
52+
host_port, database = rest.split('/', 1)
53+
54+
if ':' in host_port:
55+
host, port = host_port.split(':', 1)
56+
else:
57+
host = host_port
58+
port = 3306 # 默认MySQL端口
59+
60+
return {
61+
'host': host,
62+
'port': port,
63+
'user': user,
64+
'password': password,
65+
'database': database
66+
}
67+
68+
# 直接创建数据库连接
69+
def get_connection():
70+
"""直接创建数据库连接"""
71+
config = direct_read_config()
72+
if not config:
73+
print("无法读取配置")
74+
sys.exit(1)
75+
76+
db_uri = config.get('database', {}).get('SQLALCHEMY_DATABASE_URI')
77+
if not db_uri:
78+
print("无法找到数据库URI")
79+
sys.exit(1)
80+
81+
db_info = direct_parse_db_uri(db_uri)
82+
print(f"数据库连接信息: {db_info}")
83+
84+
try:
85+
return pymysql.connect(
86+
host=db_info['host'],
87+
port=int(db_info['port']),
88+
user=db_info['user'],
89+
password=db_info['password'],
90+
database=db_info['database'],
91+
charset='utf8mb4'
92+
)
93+
except Exception as e:
94+
print(f"连接数据库失败: {str(e)}")
95+
sys.exit(1)
96+
97+
def reset_card_tables():
98+
"""重置Card模块的数据库表"""
99+
conn = get_connection()
100+
cursor = conn.cursor()
101+
102+
try:
103+
# 删除表(如果存在)
104+
cursor.execute("DROP TABLE IF EXISTS card")
105+
cursor.execute("DROP TABLE IF EXISTS cardcategory")
106+
print("已删除Card相关表")
107+
108+
# 创建cardcategory表
109+
cursor.execute("""
110+
CREATE TABLE cardcategory (
111+
id INT PRIMARY KEY,
112+
name VARCHAR(64) NOT NULL
113+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
114+
""")
115+
print("成功创建cardcategory表")
116+
117+
# 创建card表
118+
cursor.execute("""
119+
CREATE TABLE card (
120+
id INT AUTO_INCREMENT PRIMARY KEY,
121+
type INT DEFAULT 1,
122+
headline TEXT NOT NULL,
123+
content TEXT,
124+
createtime DATETIME,
125+
updatetime DATETIME,
126+
donetime DATETIME,
127+
usedtime INT DEFAULT 0,
128+
begintime DATETIME,
129+
endtime DATETIME,
130+
cardcategory_id INT DEFAULT 1,
131+
FOREIGN KEY (cardcategory_id) REFERENCES cardcategory(id)
132+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
133+
""")
134+
print("成功创建card表")
135+
136+
# 添加默认分类
137+
cursor.execute("INSERT INTO cardcategory (id, name) VALUES (1, '待办卡片')")
138+
cursor.execute("INSERT INTO cardcategory (id, name) VALUES (2, '已完成')")
139+
conn.commit()
140+
print("成功添加默认分类")
141+
142+
# 添加示例卡片
143+
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
144+
cursor.execute(f"""
145+
INSERT INTO card (headline, type, createtime, cardcategory_id)
146+
VALUES ('这是一个示例卡片', 1, '{now}', 1)
147+
""")
148+
conn.commit()
149+
print("成功添加示例卡片")
150+
except Exception as e:
151+
print(f"重置Card表出错: {str(e)}")
152+
conn.rollback()
153+
154+
cursor.close()
155+
conn.close()
156+
157+
def reset_todo_tables():
158+
"""重置Todo模块的数据库表"""
159+
conn = get_connection()
160+
cursor = conn.cursor()
161+
162+
try:
163+
# 删除表(如果存在)
164+
cursor.execute("DROP TABLE IF EXISTS todo_item")
165+
cursor.execute("DROP TABLE IF EXISTS todo_category")
166+
print("已删除Todo相关表")
167+
168+
# 创建todo_category表
169+
cursor.execute("""
170+
CREATE TABLE todo_category (
171+
id INT PRIMARY KEY,
172+
name VARCHAR(64) NOT NULL
173+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
174+
""")
175+
print("成功创建todo_category表")
176+
177+
# 创建todo_item表
178+
cursor.execute("""
179+
CREATE TABLE todo_item (
180+
id INT AUTO_INCREMENT PRIMARY KEY,
181+
body TEXT NOT NULL,
182+
category_id INT DEFAULT 1,
183+
FOREIGN KEY (category_id) REFERENCES todo_category(id)
184+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
185+
""")
186+
print("成功创建todo_item表")
187+
188+
# 添加默认分类
189+
cursor.execute("INSERT INTO todo_category (id, name) VALUES (1, '待办事项')")
190+
cursor.execute("INSERT INTO todo_category (id, name) VALUES (2, '已完成')")
191+
conn.commit()
192+
print("成功添加默认分类")
193+
194+
# 添加示例待办事项
195+
cursor.execute("""
196+
INSERT INTO todo_item (body, category_id)
197+
VALUES ('这是一个示例待办事项', 1)
198+
""")
199+
conn.commit()
200+
print("成功添加示例待办事项")
201+
except Exception as e:
202+
print(f"重置Todo表出错: {str(e)}")
203+
conn.rollback()
204+
205+
cursor.close()
206+
conn.close()
207+
208+
if __name__ == "__main__":
209+
# 询问用户要重置哪些表
210+
print("请选择要重置的表:")
211+
print("1. 重置Card相关表")
212+
print("2. 重置Todo相关表")
213+
print("3. 重置所有表")
214+
215+
choice = input("请输入选项(1/2/3): ")
216+
217+
if choice == '1':
218+
reset_card_tables()
219+
print("Card表重置完成")
220+
elif choice == '2':
221+
reset_todo_tables()
222+
print("Todo表重置完成")
223+
elif choice == '3':
224+
reset_card_tables()
225+
reset_todo_tables()
226+
print("所有表重置完成")
227+
else:
228+
print("无效选项")

0 commit comments

Comments
 (0)