views.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from rest_framework import status, permissions
  2. from rest_framework.decorators import permission_classes
  3. from rest_framework.response import Response
  4. from rest_framework.views import APIView
  5. from rest_framework.viewsets import ModelViewSet
  6. from django.contrib.auth import login, logout
  7. from django.contrib.auth.backends import ModelBackend
  8. from workreport.models import DailyReport
  9. from workreport.serializer import DailyReportSerializer
  10. class DailyReportViews(APIView):
  11. def get(self, request):
  12. data = DailyReport.objects.values('title', 'content', 'create_at', 'create_by', 'id')
  13. return Response(data=data, status=status.HTTP_200_OK)
  14. def post(self, request):
  15. data = request.data
  16. report = DailyReport(title=data['title'], content=data['content'], create_by_id=data['create_by_id'])
  17. report.save()
  18. return Response(status=status.HTTP_201_CREATED)
  19. class ReportViews(ModelViewSet):
  20. queryset = DailyReport.objects.all()
  21. serializer_class = DailyReportSerializer
  22. # search_fields '^'开始搜索。'='完全匹配。'@'全文搜索。(当前仅支持Django的MySQL后端。)'$'正则表达式搜索。
  23. filter_fields = {'title': ['exact']}
  24. @permission_classes((permissions.AllowAny,))
  25. class LoginView(APIView):
  26. def post(self, request):
  27. data = request.data
  28. user = ModelBackend().authenticate(username=data['username'], password=data['password'], request=request)
  29. if user is None:
  30. return Response(data={'msg': '用户名或密码不正确'}, status=status.HTTP_404_NOT_FOUND)
  31. else:
  32. login(request, user=user, backend='django.contrib.auth.backends.ModelBackend')
  33. return Response(status=status.HTTP_200_OK)
  34. class LogoutView(APIView):
  35. def post(self, request):
  36. logout(request)
  37. return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)