notice.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from django.views.generic import View
  5. from libs import json_response, JsonParser, Argument
  6. from apps.home.models import Notice
  7. import json
  8. class NoticeView(View):
  9. def get(self, request):
  10. notices = Notice.objects.all()
  11. return json_response([x.to_view() for x in notices])
  12. def post(self, request):
  13. form, error = JsonParser(
  14. Argument('id', type=int, required=False),
  15. Argument('title', help='请输入标题'),
  16. Argument('content', help='请输入内容'),
  17. Argument('is_stress', type=bool, default=False),
  18. ).parse(request.body)
  19. if error is None:
  20. if form.is_stress:
  21. Notice.objects.update(is_stress=False)
  22. if form.id:
  23. Notice.objects.filter(pk=form.id).update(**form)
  24. else:
  25. notice = Notice.objects.create(**form)
  26. notice.sort_id = notice.id
  27. notice.save()
  28. return json_response(error=error)
  29. def patch(self, request):
  30. form, error = JsonParser(
  31. Argument('id', type=int, help='参数错误'),
  32. Argument('sort', filter=lambda x: x in ('up', 'down'), required=False),
  33. Argument('read', required=False)
  34. ).parse(request.body)
  35. if error is None:
  36. notice = Notice.objects.filter(pk=form.id).first()
  37. if not notice:
  38. return json_response(error='未找到指定记录')
  39. if form.sort:
  40. if form.sort == 'up':
  41. tmp = Notice.objects.filter(sort_id__gt=notice.sort_id).last()
  42. else:
  43. tmp = Notice.objects.filter(sort_id__lt=notice.sort_id).first()
  44. if tmp:
  45. tmp.sort_id, notice.sort_id = notice.sort_id, tmp.sort_id
  46. tmp.save()
  47. if form.read:
  48. read_ids = json.loads(notice.read_ids)
  49. read_ids.append(str(request.user.id))
  50. notice.read_ids = json.dumps(read_ids)
  51. notice.save()
  52. return json_response(error=error)
  53. def delete(self, request):
  54. form, error = JsonParser(
  55. Argument('id', type=int, help='参数错误')
  56. ).parse(request.GET)
  57. if error is None:
  58. Notice.objects.filter(pk=form.id).delete()
  59. return json_response(error=error)