views.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from django.contrib.auth import login, logout
  2. from django.contrib.auth.backends import ModelBackend
  3. from django.shortcuts import render
  4. # Create your views here.
  5. from rest_framework import status, permissions
  6. from rest_framework.decorators import permission_classes
  7. from rest_framework.response import Response
  8. from rest_framework.views import APIView
  9. from rest_framework.viewsets import ModelViewSet
  10. from workreport.models import DailyReport
  11. # api接口调用方法
  12. from workreport.serializex import DailyReportSerializex
  13. class ReportView(APIView):
  14. # get 请求
  15. def get(self, request):
  16. # 取字段
  17. data = DailyReport \
  18. .objects \
  19. .values().all()
  20. # .values('title', 'content', 'creat_at', 'creat_by', 'id')
  21. # 返回请求 数据和请求状态
  22. return Response(data=data, status=status.HTTP_200_OK)
  23. # post 请求
  24. def post(self, request):
  25. # DailyReport
  26. data = request.data
  27. # 存入数据库
  28. # 设置保存内容
  29. report = DailyReport(
  30. title=data['title'],
  31. content=data['content'],
  32. creat_by_id=data['creat_by_id'],
  33. )
  34. report.save() # 执行了保存操作
  35. return Response(status=status.HTTP_201_CREATED)
  36. # delete 请求
  37. def delete(self, request):
  38. data = request.data
  39. report = DailyReport \
  40. .objects \
  41. .filter(creat_by_id=data['creat_by_id']) \
  42. .delete()
  43. return Response(data=report, status=status.HTTP_200_OK)
  44. # update 请求
  45. def put(self, request):
  46. data = request.data
  47. report = DailyReport \
  48. .objects \
  49. .filter(creat_by_id=data['creat_by_id']) \
  50. .update(content="改变内容")
  51. return Response(data=report, status=status.HTTP_200_OK)
  52. class DailyReportView(ModelViewSet):
  53. queryset = DailyReport.objects.all()
  54. serializer_class = DailyReportSerializex
  55. filter_fields = {'title': ['exact']}
  56. @permission_classes((permissions.AllowAny,))
  57. class LoginView(APIView):
  58. def post(self, request):
  59. data = request.data
  60. user = ModelBackend().authenticate(username=data['username'], password=data['password'], request=request)
  61. if user is None:
  62. return Response(data={'msg': '用户名或密码不正确'}, status=status.HTTP_404_NOT_FOUND)
  63. else:
  64. login(request, user=user, backend='django.contrib.auth.backends.ModelBackend')
  65. return Response(status=status.HTTP_200_OK)
  66. class LogoutView(APIView):
  67. def post(self, request):
  68. logout(request)
  69. return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)