yj
2026-03-31 4becf7b5eba5de2d9889f379eb88aeb6cb16f760
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import json
from flask import Flask, request, jsonify
from database import DatabaseConfig, init_database
from dao import ContentTypeDAO, ContentDAO
import logging
from datetime import datetime
from flask_cors import CORS
 
# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
 
# 加载配置
with open("config.json") as f:
    config = json.load(f)
 
app = Flask(__name__)
CORS(app)
 
# 初始化数据库
db_config = DatabaseConfig()
init_database()  # 初始化数据库和表(如果不存在)
 
 
# 新的API端点:ContentType相关
@app.route("/api/v1/type/save", methods=["POST"])
def save_contenttype():
    """保存ContentType的API端点"""
    connection = None
    try:
        # 从请求中获取JSON数据
        data = request.get_json()
 
        if not data:
            return jsonify({"error": "未提供数据"}), 400
 
        # 检查是否是单个对象还是列表
        if isinstance(data, list):
            # 处理多个记录 - 使用单个连接和事务
            connection = db_config.get_connection()
            if not connection:
                return jsonify({"error": "数据库连接失败"}), 500
 
            results = []
            errors = []
            try:
                for i, item in enumerate(data):
                    # 为每个项目创建一个包含数据库连接的配置
                    class TempDbConfig:
                        def get_connection(self):
                            return connection
 
                    result, error = ContentTypeDAO.save_contenttype(
                        item, TempDbConfig()
                    )
                    if error:
                        errors.append({"index": i, "error": error, "data": item})
                    else:
                        results.append(result)
 
                connection.commit()  # 提交所有更改
 
                response_data = {
                    "saved": results,
                    "errors": errors,
                    "total_saved": len(results),
                }
                if errors:
                    # 如果有错误,返回400状态码
                    status_code = (
                        400
                        if any(
                            err["error"] in ["代码已存在", "代码和名称是必需的"]
                            for err in errors
                        )
                        else 500
                    )
                    return jsonify(response_data), status_code
                else:
                    # 如果没有错误,检查是否有更新的记录
                    has_updates = any("更新" in r["message"] for r in results)
                    return jsonify(response_data), 200 if has_updates else 201
            except Exception as e:
                if connection:
                    connection.rollback()
                logger.error(f"批量保存ContentType时出错: {e}")
                return jsonify({"error": "批量保存操作失败"}), 500
            finally:
                if connection:
                    connection.close()
        else:
            # 处理单个记录
            result, error = ContentTypeDAO.save_contenttype(data, db_config)
 
            if error:
                if error == "代码已存在" or error == "代码和名称是必需的":
                    return jsonify({"error": error}), 400
                else:
                    return jsonify({"error": error}), 500
 
            return jsonify(result), 200 if "更新" in result["message"] else 201
 
    except Exception as e:
        if connection:
            try:
                connection.rollback()
                connection.close()
            except Exception as close_error:
                logger.error(f"关闭连接时出错: {close_error}")
        logger.error(f"save_contenttype中的意外错误: {e}")
        return jsonify({"error": "无效的请求格式"}), 400
 
 
@app.route("/api/v1/type/get", methods=["GET"])
def get_contenttype():
    """从数据库检索ContentType的API端点"""
    try:
        # 获取查询参数
        code = request.args.get("code", "").strip()
        record_id = request.args.get("id")
        limit = request.args.get("limit", type=int)
 
        # 验证参数
        if record_id and not record_id.isdigit():
            return jsonify({"error": "无效的ID参数"}), 400
 
        if limit and limit <= 0:
            return jsonify({"error": "限制必须是正整数"}), 400
 
        # 使用DAO进行数据库操作
        result, error = ContentTypeDAO.get_contenttype(
            contenttype=record_id, code=code, limit=limit, db_config=db_config
        )
 
        if error:
            return jsonify({"error": error}), 500
 
        result["timestamp"] = datetime.now().isoformat()
        return jsonify(result), 200
 
    except Exception as e:
        logger.error(f"get_contenttype中的意外错误: {e}")
        return jsonify({"error": "无效的请求参数"}), 400
 
 
# 新的API端点:Content相关
@app.route("/api/v1/content/save", methods=["POST"])
def save_content():
    """保存Content的API端点"""
    connection = None
    try:
        # 从请求中获取JSON数据
        data = request.get_json()
 
        if not data:
            return jsonify({"error": "未提供数据"}), 400
 
        # 检查是否是单个对象还是列表
        if isinstance(data, list):
            # 处理多个记录 - 使用单个连接和事务
            connection = db_config.get_connection()
            if not connection:
                return jsonify({"error": "数据库连接失败"}), 500
 
            results = []
            errors = []
            try:
                for i, item in enumerate(data):
                    # 为每个项目创建一个包含数据库连接的配置
                    class TempDbConfig:
                        def get_connection(self):
                            return connection
 
                    result, error = ContentDAO.save_content(item, TempDbConfig())
                    if error:
                        errors.append({"index": i, "error": error, "data": item})
                    else:
                        results.append(result)
 
                connection.commit()  # 提交所有更改
 
                response_data = {
                    "saved": results,
                    "errors": errors,
                    "total_saved": len(results),
                }
                if errors:
                    # 如果有错误,返回400状态码
                    status_code = (
                        400
                        if any(
                            err["error"]
                            in ["类型、问题和答案是必需的", "指定的类型ID不存在"]
                            for err in errors
                        )
                        else 500
                    )
                    return jsonify(response_data), status_code
                else:
                    return jsonify(response_data), 201
            except Exception as e:
                if connection:
                    connection.rollback()
                logger.error(f"批量保存Content时出错: {e}")
                return jsonify({"error": "批量保存操作失败"}), 500
            finally:
                if connection:
                    connection.close()
        else:
            # 处理单个记录
            result, error = ContentDAO.save_content(data, db_config)
 
            if error:
                if error in ["类型、问题和答案是必需的", "指定的类型ID不存在"]:
                    return jsonify({"error": error}), 400
                else:
                    return jsonify({"error": error}), 500
 
            return jsonify(result), 201 if "更新" not in result["message"] else 200
 
    except Exception as e:
        if connection:
            try:
                connection.rollback()
                connection.close()
            except Exception as close_error:
                logger.error(f"关闭连接时出错: {close_error}")
        logger.error(f"save_content中的意外错误: {e}")
        return jsonify({"error": "无效的请求格式"}), 400
 
 
@app.route("/api/v1/content/get", methods=["GET"])
def get_content():
    """从数据库检索Content的API端点"""
    try:
        # 获取查询参数
        content_type = request.args.get("type", type=int)
        record_id = request.args.get("id", type=int)
        limit = request.args.get("limit", type=int)
 
        # 验证参数
        if record_id and record_id <= 0:
            return jsonify({"error": "无效的ID参数"}), 400
 
        if limit and limit <= 0:
            return jsonify({"error": "限制必须是正整数"}), 400
 
        # 使用DAO进行数据库操作
        result, error = ContentDAO.get_content(
            content_id=record_id,
            content_type=content_type,
            limit=limit,
            db_config=db_config,
        )
 
        if error:
            return jsonify({"error": error}), 500
 
        result["timestamp"] = datetime.now().isoformat()
        return jsonify(result), 200
 
    except Exception as e:
        logger.error(f"get_content中的意外错误: {e}")
        return jsonify({"error": "无效的请求参数"}), 400
 
 
@app.route("/api/v1/content/delete", methods=["DELETE"])
def delete_content():
    """根据ID删除Content的API端点"""
    try:
        # 从请求中获取JSON数据
        data = request.get_json()
        if not data:
            # 也可以从URL参数获取ID
            content_id = request.args.get("id", type=int)
            if content_id is None:
                return jsonify({"error": "未提供数据或ID参数"}), 400
        else:
            # 从JSON数据中获取ID
            content_id = data.get("id")
            if content_id is None or not isinstance(content_id, int) or content_id <= 0:
                return jsonify({"error": "ID是必需的,且必须是正整数"}), 400
 
        # 使用DAO进行删除操作
        result, error = ContentDAO.delete_content(content_id, db_config)
 
        if error:
            if error == "指定的ID不存在":
                return jsonify({"error": error}), 404
            else:
                return jsonify({"error": error}), 500
 
        return jsonify(result), 200
    except Exception as e:
        logger.error(f"delete_content中的意外错误: {e}")
        return jsonify({"error": "无效的请求格式"}), 400
 
 
# 健康检查端点
@app.route("/health", methods=["GET"])
def health_check():
    """健康检查端点,验证服务是否正在运行"""
    return (
        jsonify(
            {
                "status": "OK",
                "message": "服务正在运行",
                "timestamp": datetime.now().isoformat(),
            }
        ),
        200,
    )
 
 
if __name__ == "__main__":
    # 获取服务器配置
    server_config = config["server"]
    logger.info(f"在 {server_config['host']}:{server_config['port']} 上启动服务器")
    app.run(
        host=server_config["host"],
        port=server_config["port"],
        debug=server_config["debug"],
    )