Changeset View
Changeset View
Standalone View
Standalone View
blog/views/api/comment.py
| """Implements blog post comments API.""" | |||||
| import json | import json | ||||
| from typing import Optional | from typing import Optional | ||||
| from django.contrib.auth.decorators import login_required | from django.contrib.auth.decorators import login_required | ||||
| from django.db import transaction | from django.db import transaction | ||||
| from django.http.request import HttpRequest | from django.http.request import HttpRequest | ||||
| from django.http.response import JsonResponse | from django.http.response import JsonResponse | ||||
| from django.views.decorators.http import require_POST | from django.views.decorators.http import require_POST | ||||
| from blog.models import PostComment | from blog.models import PostComment | ||||
| from comments.models import Comment | from comments.models import Comment | ||||
| from common.shortcodes import render as with_shortcodes | from common.shortcodes import render as with_shortcodes | ||||
| from common.types import assert_cast | from common.types import assert_cast | ||||
| @require_POST | @require_POST | ||||
| @login_required | @login_required | ||||
| def comment(request: HttpRequest, *, post_pk: int) -> JsonResponse: | def comment(request: HttpRequest, *, post_pk: int) -> JsonResponse: | ||||
| """Add a top-level comment under a blog post or a reply to another comment.""" | |||||
| parsed_body = json.loads(request.body) | parsed_body = json.loads(request.body) | ||||
| reply_to_pk = None if parsed_body['reply_to'] is None else int(parsed_body['reply_to']) | reply_to_pk = int(parsed_body['reply_to']) if parsed_body.get('reply_to') else None | ||||
sybren: Do you want to accept `{"reply_to": undefined}` in the JSON? If not, you can replace… | |||||
| message = assert_cast(str, parsed_body['message']) | message = assert_cast(str, parsed_body['message']) | ||||
| @transaction.atomic | @transaction.atomic | ||||
| def create_comment( | def create_comment( | ||||
| *, user_pk: int, post_pk: int, message: str, reply_to_pk: Optional[int] | *, user_pk: int, post_pk: int, message: str, reply_to_pk: Optional[int] | ||||
| ) -> Comment: | ) -> Comment: | ||||
| comment = Comment.objects.create(user_id=user_pk, message=message, reply_to_id=reply_to_pk) | comment = Comment.objects.create(user_id=user_pk, message=message, reply_to_id=reply_to_pk) | ||||
| PostComment.objects.create(comment_id=comment.id, post_id=post_pk) | PostComment.objects.create(comment_id=comment.id, post_id=post_pk) | ||||
| Show All 21 Lines | |||||
Do you want to accept {"reply_to": undefined} in the JSON? If not, you can replace parsed_body.get('reply_to') is None with simply 'reply_to' in parsed_body.