AI智能
改变未来

Django学习1


安装Django

pip install django==2.2.0#pip install djangorestframework

基础函数视图

#!/usr/bin/env/python# --*-- coding:utf-8 --*--# Author: Vaedit# @Time:from django.http import HttpResponsefrom django.http import JsonResponse,Http404from django.views.decorators.csrf import csrf_exempt # 解决跨域@csrf_exemptdef 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()

类视图继承View

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\")
from django.http import HttpResponsefrom django.http import JsonResponse,Http404from django.views.decorators.csrf import csrf_exempt # 解决跨域import jsonfrom .models import TestDataretdata = {\"code\": 0,\"data\": None,\"message\": \"\"}class TestViewV3(View):def get_object(self, pk):try:obj = TestData.objects.get(pk=pk) # 获取单条数据对象except Publisher.DoesNotExist as e:raise Http404()return objdef get(self, request, *args, **kwargs):# 如果有pk,则返回单条数据详情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_dictreturn JsonResponse(retdata)else:# 返回数据列表,所有数据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_listreturn JsonResponse(retdata, safe=False)def post(self, request, *args, **kwargs):if request.content_type == \'application/json\':data = request.body # 获取post请求内容print(data)try:data = json.loads(data)print(data)except Exception as e:retdata[\'code\'] = -1retdata[\'message\'] = ereturn JsonResponse(retdata)elif request.content_type == \'application/x-www-form-urlencoded\':data = request.POST.dict()print(request.POST)else:retdata[\'code\'] = -1retdata[\'data\'] = \"\"retdata[\'message\'] = \"Content-Type不支持当前\"return JsonResponse(retdata)try:p = TestData.objects.create(**data) # 创建数据except Exception as e:retdata[\'code\'] = -1retdata[\'message\'] = \"TestData create err {}\".format(e)return JsonResponse(retdata)else:data[\'pk\'] = p.pkretdata[\"data\"] = datareturn JsonResponse(retdata)def put(self, request, *args, **kwargs):pk = kwargs.get(\'pk\')self.get_object(pk)if request.content_type == \'application/json\':data = request.bodytry:data = json.loads(data)except Exception as e:retdata[\'code\'] = -1retdata[\'message\'] = ereturn JsonResponse(retdata)elif request.content_type == \'application/x-www-form-urlencoded\':data = request.POST.dict()print(data)else:retdata[\'code\'] = -1retdata[\'message\'] = \"Content-Type不支持当前\"return JsonResponse(retdata)try:TestData.objects.filter(pk=pk).update(**data) # 更新内容except Exception as e:retdata[\'code\'] = -1retdata[\'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() 删除数据except Exception as e:retdata[\'code\'] = -1retdata[\'message\'] = \'Delete pk {} err {}.\'.format(pk, e)return JsonResponse(retdata)else:return JsonResponse(retdata)
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Django学习1