Install Django

PIP install django = = 2.2.0#pip install djangorestframework
Copy the code

Basic function view

#! /usr/bin/env/python
# --*-- coding:utf-8 --*--
# Author: Vaedit
# @Time: 

from django.http import HttpResponse
from django.http import JsonResponse,Http404
from django.views.decorators.csrf import csrf_exempt # Resolve cross-domain

@csrf_exempt 
def TestView(request, *args, **kwargs) :
    #return HttpResponse("ok")
    print(request.method)
    if request.method == 'GET':
        return HttpResponse("GET")
    elif request.method == 'POST':
        return HttpResponse("POST")

    elif request.method == 'PUT':
        return HttpResponse("PUT")

    elif request.method == 'DELETE':
        return HttpResponse("DELETE")
    else:
        raise Http404()
Copy the code

Class views inherit from Views

class TestViewV2(View) :
    def get(self,request,*args,**kwargs) :
        print(request.GET)
        return HttpResponse("GET view V2")
    def post(self, request, *args, **kwargs) :
        # print(request.body)
        print(request.POST)
        return HttpResponse("POST view v2")

    def put(self, request, *args, **kwargs) :
        return HttpResponse("PUT view v2")

    def delete(self, request, *args, **kwargs) :
        return HttpResponse("DELETE view v2")
Copy the code
from django.http import HttpResponse
from django.http import JsonResponse,Http404
from django.views.decorators.csrf import csrf_exempt # Resolve cross-domain
import json
from .models import TestData
retdata = {
    "code": 0."data": None."message": ""
}

class TestViewV3(View) :

    def get_object(self, pk) :
        try:
            obj = TestData.objects.get(pk=pk) Get a single data object
        except Publisher.DoesNotExist as e:
            raise Http404()
        return obj

    def get(self, request, *args, **kwargs) :
        If there is a pk, return a single data detail
        pk = kwargs.get('pk')
        if pk:
            obj = self.get_object(pk)
            _data_dict = {
                "pk": obj.pk,
                "name": obj.name,
                "address": obj.address,
            }
            retdata['data'] = _data_dict
            return JsonResponse(retdata)
        else:
            # return list of data, all data
            objs = TestData.objects.all()
            _data_list = []
            for obj in objs:
                _data_list.append({
                    "pk": obj.pk,
                    "name": obj.name,
                    "address": obj.address,
                })
            retdata["data"] = _data_list
            return JsonResponse(retdata, safe=False)

    def post(self, request, *args, **kwargs) :
        if request.content_type == 'application/json': 
            data = request.body Get the post request content
            print(data)
            try:
                data = json.loads(data)
                print(data)
            except Exception as e:
                retdata['code'] = -1
                retdata['message'] = e
                return JsonResponse(retdata)
        elif request.content_type == 'application/x-www-form-urlencoded':
            data = request.POST.dict(a)print(request.POST)
        else:
            retdata['code'] = -1
            retdata['data'] = ""
            retdata['message'] = "Content-type not currently supported"
            return JsonResponse(retdata)
        try:
            p = TestData.objects.create(**data) # create data
        except Exception as e:
            retdata['code'] = -1
            retdata['message'] = "TestData create err {}".format(e)
            return JsonResponse(retdata)
        else:
            data['pk'] = p.pk
            retdata["data"] = data
            return JsonResponse(retdata)

    def put(self, request, *args, **kwargs) :
        pk = kwargs.get('pk')
        self.get_object(pk)
        if request.content_type == 'application/json':
            data = request.body
            try:
                data = json.loads(data)
            except Exception as e:
                retdata['code'] = -1
                retdata['message'] = e
                return JsonResponse(retdata)
        elif request.content_type == 'application/x-www-form-urlencoded':
            data = request.POST.dict(a)print(data)
        else:
            retdata['code'] = -1
            retdata['message'] = "Content-type not currently supported"
            return JsonResponse(retdata)

        try:
            TestData.objects.filter(pk=pk).update(**data) # Update content
        except Exception as e:
            retdata['code'] = -1
            retdata['message'] = 'Update pk {} err {}.'.format(pk, e)
            return JsonResponse(retdata)
        else:
            return JsonResponse(retdata)

    def delete(self, request, *args, **kwargs) :
        pk = kwargs.get('pk')
        self.get_object(pk)

        try: testdata.objects.get (pk=pk).delete() deletes dataexcept Exception as e:
            retdata['code'] = -1
            retdata['message'] = 'Delete pk {} err {}.'.format(pk, e)
            return JsonResponse(retdata)
        else:
            return JsonResponse(retdata)
Copy the code