blob: 2d5b6544413e4ec0143b368099faa258c6cba0bc [file] [log] [blame]
wueb6e6ca2025-06-15 10:35:32 +08001# routes/comments.py
2from flask import Blueprint, request, jsonify, abort
3from extensions import db
4from models.comment import Comment
5from models.behavior import Behavior
6
7comments_bp = Blueprint('comments', __name__)
8
9@comments_bp.route('', methods=['POST'])
10def 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'])
31def 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])