| # routes/comments.py |
| from flask import Blueprint, request, jsonify, abort |
| from extensions import db |
| from models.comment import Comment |
| from models.behavior import Behavior |
| |
| comments_bp = Blueprint('comments', __name__) |
| |
| @comments_bp.route('', methods=['POST']) |
| def add_comment(post_id): |
| data = request.get_json() or {} |
| user_id = data.get('user_id') |
| content = data.get('content') |
| if not user_id or not content: |
| return jsonify({'error': 'user_id and content required'}), 400 |
| |
| comment = Comment( |
| post_id=post_id, |
| user_id=user_id, |
| content=content, |
| parent_id=data.get('parent_id') |
| ) |
| db.session.add(comment) |
| # 记录行为 |
| beh = Behavior(user_id=user_id, post_id=post_id, type='comment') |
| db.session.add(beh) |
| db.session.commit() |
| return jsonify({'id': comment.id}), 201 |
| |
| @comments_bp.route('', methods=['GET']) |
| def list_comments(post_id): |
| def serialize(c): |
| return { |
| 'id': c.id, |
| 'user_id': c.user_id, |
| 'content': c.content, |
| 'created_at': c.created_at.isoformat(), |
| 'replies': [serialize(r) for r in c.replies] |
| } |
| |
| comments = Comment.query.filter_by( |
| post_id=post_id, |
| status='active', |
| parent_id=None |
| ).order_by(Comment.created_at.asc()).all() |
| return jsonify([serialize(c) for c in comments]) |