from django.contrib.auth import login, logout from django.contrib.auth.backends import ModelBackend from django.shortcuts import render # Create your views here. from rest_framework import status, permissions from rest_framework.decorators import permission_classes from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from workreport.models import DailyReport # api接口调用方法 from workreport.serializex import DailyReportSerializex class ReportView(APIView): # get 请求 def get(self, request): # 取字段 data = DailyReport \ .objects \ .values().all() # .values('title', 'content', 'creat_at', 'creat_by', 'id') # 返回请求 数据和请求状态 return Response(data=data, status=status.HTTP_200_OK) # post 请求 def post(self, request): # DailyReport data = request.data # 存入数据库 # 设置保存内容 report = DailyReport( title=data['title'], content=data['content'], creat_by_id=data['creat_by_id'], ) report.save() # 执行了保存操作 return Response(status=status.HTTP_201_CREATED) # delete 请求 def delete(self, request): data = request.data report = DailyReport \ .objects \ .filter(creat_by_id=data['creat_by_id']) \ .delete() return Response(data=report, status=status.HTTP_200_OK) # update 请求 def put(self, request): data = request.data report = DailyReport \ .objects \ .filter(creat_by_id=data['creat_by_id']) \ .update(content="改变内容") return Response(data=report, status=status.HTTP_200_OK) class DailyReportView(ModelViewSet): queryset = DailyReport.objects.all() serializer_class = DailyReportSerializex filter_fields = {'title': ['exact']} @permission_classes((permissions.AllowAny,)) class LoginView(APIView): def post(self, request): data = request.data user = ModelBackend().authenticate(username=data['username'], password=data['password'], request=request) if user is None: return Response(data={'msg': '用户名或密码不正确'}, status=status.HTTP_404_NOT_FOUND) else: login(request, user=user, backend='django.contrib.auth.backends.ModelBackend') return Response(status=status.HTTP_200_OK) class LogoutView(APIView): def post(self, request): logout(request) return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)