wu | eb6e6ca | 2025-06-15 10:35:32 +0800 | [diff] [blame] | 1 | # routes/comments.py |
| 2 | from flask import Blueprint, request, jsonify, abort |
| 3 | from extensions import db |
| 4 | from models.comment import Comment |
| 5 | from models.behavior import Behavior |
| 6 | |
| 7 | comments_bp = Blueprint('comments', __name__) |
| 8 | |
| 9 | @comments_bp.route('', methods=['POST']) |
| 10 | def add_comment(post_id): |
| 11 | data = request.get_json() or {} |
| 12 | user_id = data.get('user_id') |
| 13 | content = data.get('content') |
| 14 | if not user_id or not content: |
| 15 | return jsonify({'error': 'user_id and content required'}), 400 |
| 16 | |
| 17 | comment = Comment( |
| 18 | post_id=post_id, |
| 19 | user_id=user_id, |
| 20 | content=content, |
| 21 | parent_id=data.get('parent_id') |
| 22 | ) |
| 23 | db.session.add(comment) |
| 24 | # 记录行为 |
| 25 | beh = Behavior(user_id=user_id, post_id=post_id, type='comment') |
| 26 | db.session.add(beh) |
| 27 | db.session.commit() |
| 28 | return jsonify({'id': comment.id}), 201 |
| 29 | |
| 30 | @comments_bp.route('', methods=['GET']) |
| 31 | def list_comments(post_id): |
| 32 | def serialize(c): |
| 33 | return { |
| 34 | 'id': c.id, |
| 35 | 'user_id': c.user_id, |
| 36 | 'content': c.content, |
| 37 | 'created_at': c.created_at.isoformat(), |
| 38 | 'replies': [serialize(r) for r in c.replies] |
| 39 | } |
| 40 | |
| 41 | comments = Comment.query.filter_by( |
| 42 | post_id=post_id, |
| 43 | status='active', |
| 44 | parent_id=None |
| 45 | ).order_by(Comment.created_at.asc()).all() |
| 46 | return jsonify([serialize(c) for c in comments]) |