from flask import request, jsonify from utils.database import get_db from utils.auth import admin_required def register_news_routes(app): @app.route('/api/news', methods=['GET']) def get_news(): page = int(request.args.get('page', 1)) limit = int(request.args.get('limit', 10)) offset = (page - 1) * limit conn = get_db() cursor = conn.cursor() try: cursor.execute('SELECT COUNT(*) FROM news WHERE status = "published"') total = cursor.fetchone()[0] cursor.execute(''' SELECT * FROM news WHERE status = "published" ORDER BY sort_order ASC, created_at DESC LIMIT ? OFFSET ? ''', (limit, offset)) rows = cursor.fetchall() items = [dict(row) for row in rows] return jsonify({'items': items, 'total': total, 'page': page, 'limit': limit}) finally: conn.close() @app.route('/api/news/', methods=['GET']) def get_news_item(news_id): conn = get_db() cursor = conn.cursor() try: cursor.execute('SELECT * FROM news WHERE id = ? AND status = "published"', (news_id,)) row = cursor.fetchone() if row: return jsonify(dict(row)) else: return jsonify({'error': '资讯不存在'}), 404 finally: conn.close() @app.route('/api/news/', methods=['PUT']) @admin_required def update_news(news_id): data = request.json if not data.get('title'): return jsonify({'error': '标题不能为空'}), 400 conn = get_db() cursor = conn.cursor() try: cursor.execute(''' UPDATE news SET title = ?, summary = ?, content = ?, image_url = ?, status = ?, sort_order = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? ''', ( data.get('title'), data.get('summary', ''), data.get('content', ''), data.get('image_url', ''), data.get('status', 'draft'), data.get('sort_order', 0), news_id )) conn.commit() if cursor.rowcount == 0: return jsonify({'error': '资讯不存在'}), 404 return jsonify({'success': True}) except Exception as e: conn.rollback() raise e finally: conn.close() @app.route('/api/news', methods=['POST']) @admin_required def create_news(): data = request.json if not data.get('title'): return jsonify({'error': '标题不能为空'}), 400 conn = get_db() cursor = conn.cursor() try: cursor.execute(''' INSERT INTO news (title, summary, content, image_url, status, sort_order) VALUES (?, ?, ?, ?, ?, ?) ''', ( data.get('title'), data.get('summary', ''), data.get('content', ''), data.get('image_url', ''), data.get('status', 'draft'), data.get('sort_order', 0) )) news_id = cursor.lastrowid conn.commit() return jsonify({'id': news_id, 'success': True}) except Exception as e: conn.rollback() raise e finally: conn.close() @app.route('/api/news/', methods=['DELETE']) @admin_required def delete_news(news_id): conn = get_db() cursor = conn.cursor() try: cursor.execute('DELETE FROM news WHERE id = ?', (news_id,)) conn.commit() if cursor.rowcount == 0: return jsonify({'error': '资讯不存在'}), 404 return jsonify({'success': True, 'message': '删除成功'}) except Exception as e: conn.rollback() raise e finally: conn.close()