views.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import kwargs as kwargs
  2. from django.contrib.auth import login, logout
  3. from django.contrib.auth.backends import ModelBackend
  4. from rest_framework import status, permissions
  5. from rest_framework.decorators import permission_classes
  6. from rest_framework.response import Response
  7. from rest_framework.views import APIView
  8. from rest_framework.viewsets import ModelViewSet
  9. from workreport.models import DailyReport
  10. from workreport.serializers import DailyReportSerialiser
  11. class ReportView(APIView):
  12. def get(self, request):
  13. data = DailyReport.objects.values('title', 'content', 'content', 'create_at', 'id')
  14. return Response(data=data, status=status.HTTP_200_OK)
  15. def post(self, request):
  16. data = request.data
  17. report = DailyReport(title=data['title'], content=data['content'], create_by_id=data['create_by_id'])
  18. report.save()
  19. return Response(status=status.HTTP_201_CREATED)
  20. def delete(self, instance):
  21. pass
  22. class DailyReportView(ModelViewSet):
  23. queryset = DailyReport.objects.all()
  24. serializer_class = DailyReportSerialiser
  25. filter_fields = {'title': ['exact']}
  26. def update(self, request, *args, **kwargs):
  27. kwargs['partial'] = True
  28. return super().update(request, *args, **kwargs)
  29. # 登入,权限配置
  30. @permission_classes((permissions.AllowAny,))
  31. class LoginView(APIView):
  32. def post(self, request):
  33. data = request.data
  34. user = ModelBackend().authenticate(username=data['username'], password=data['password'], request=request)
  35. # user = authenticate(username=data['username'], password=data['password'], request=request)
  36. if user is None:
  37. return Response(data={'msg': '用户名或密码不正确'}, status=status.HTTP_404_NOT_FOUND)
  38. else:
  39. login(request, user=user, backend='django.contrib.auth.backends.ModelBackend')
  40. # login(request, user=user)
  41. return Response(status=status.HTTP_200_OK, data={'user_id': user.id})
  42. class LogoutView(APIView):
  43. def post(self, request):
  44. logout(request)
  45. return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)