码迷,mamicode.com
首页 > 其他好文 > 详细

Django学习1

时间:2020-11-27 11:21:56      阅读:8      评论:0      收藏:0      [点我收藏+]

标签:not   www   ==   decorator   exist   load   python   int   数据   

安装Django
pip install django==2.2.0
#pip install djangorestframework

基础函数视图

#!/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 # 解决跨域

@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()

类视图继承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 HttpResponse
from django.http import JsonResponse,Http404
from django.views.decorators.csrf import csrf_exempt # 解决跨域
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) # 获取单条数据对象
        except Publisher.DoesNotExist as e:
            raise Http404()
        return obj

    def 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_dict
            return 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_list
            return 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‘] = -1
                retdata[‘message‘] = e
                return JsonResponse(retdata)
        elif request.content_type == ‘application/x-www-form-urlencoded‘:
            data = request.POST.dict()
            print(request.POST)
        else:
            retdata[‘code‘] = -1
            retdata[‘data‘] = ""
            retdata[‘message‘] = "Content-Type不支持当前"
            return JsonResponse(retdata)
        try:
            p = TestData.objects.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()
            print(data)
        else:
            retdata[‘code‘] = -1
            retdata[‘message‘] = "Content-Type不支持当前"
            return JsonResponse(retdata)

        try:
            TestData.objects.filter(pk=pk).update(**data) # 更新内容
        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() 删除数据
        except Exception as e:
            retdata[‘code‘] = -1
            retdata[‘message‘] = ‘Delete pk {} err {}.‘.format(pk, e)
            return JsonResponse(retdata)
        else:
            return JsonResponse(retdata)

Django学习1

标签:not   www   ==   decorator   exist   load   python   int   数据   

原文地址:https://blog.51cto.com/vaedit/2553674

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!