通用视图-分开处理GET、POST请求

1.编辑urls.py:

    url(r'^vmmgmt-vms/$', views.vmmgmt,{'model':models.hvvms,'GET': views.vmmgmt_get_view,'POST': views.vmmgmt_post_view},name='vmmgmt-vms'), #vmmgmt view接收model,GET,POST参数
    url(r'^vmmgmt-hv/$', views.vmmgmt,{'model':models.hvsrvs,'GET': views.vmmgmt_get_view,'POST': views.vmmgmt_post_view},name='vmmgmt-hv'),
    url(r'^vmmgmt-vhd/$', views.vmmgmt,{'model':models.hvvhds,'GET': views.vmmgmt_get_view,'POST': views.vmmgmt_post_view},name='vmmgmt-vhd'),

2.编辑views.py:

#split get and post requests.
def vmmgmt(request,*args,**kwargs): #从url接收参数,用于区分GET、POST请求
    vmmgmt_get_view = kwargs.pop('GET', None) #return None if GET not exists.
    vmmgmt_post_view = kwargs.pop('POST', None)
    model = kwargs.pop('model', None) #获取当前model
    if request.method == 'GET' and vmmgmt_get_view is not None: #GET请求返回到vmmgmt_get_view()函数进行处理
        return vmmgmt_get_view(request, model) #将model传递到get view
    elif request.method == 'POST' and vmmgmt_post_view is not None:
        return vmmgmt_post_view(request, model)
        #return vmmgmt_post_view(request, *args, **kwargs)
    raise Http404

#handle get request.
def vmmgmt_get_view(request,model):
    obj_list = model.objects.all()  #从url中的 model 参数接收到具体的model类。模板中要使用 obj_list 变量做for循环
    counts = model.objects.count()
    assert request.method == 'GET'
    if 'q-hv' in request.GET:
            qdata = request.GET['q-hv']
            if qdata is not None:
                obj_list = model.objects.filter(serverip__icontains=qdata)
                counts = len(obj_list)

    if 'q-vms' in request.GET: #Query vm infors.
        qdata = request.GET['q-vms']
        if qdata is not None:
            obj_list = model.objects.filter(Name__icontains=qdata)
            print obj_list
            counts = len(obj_list)

    context={'obj_list':obj_list,'counts':counts}
    template_name = 'sinfors/vmmgmt_%s.html'  % model.__name__.lower()  # 每个Python的类都有一个 __name__ 属性返回类名。 这特性在当我们直到运行时刻才知道对象类型的这种情况下很有用。 比如, hvvms 类的 __name__ 就是字符串 'hvvms' 。
    #return render_to_response(template_name,context) #无法接收csrfmiddretoken参数
    return render(request,template_name,context)

#handle post request.
def vmmgmt_post_view(request,model):
    assert request.method == 'POST'
    if request.POST['posttype'].strip() == 'hvservers_update_create': #update hv servers infors.
            sdict = {}
            sdict['serverip'] = request.POST['serverip'].strip()
            sdict['servername'] = request.POST['servername'].strip()
            model.objects.update_or_create(serverip=sdict['serverip'],defaults=sdict)
            return HttpResponse(json.dumps({'sts':"修改成功"}))

    if request.POST['posttype'].strip() == 'vhds_update_create': #update vhd servers infors.
        sdict = {}
        sdict['vhdname'] = request.POST['vhdname'].strip()
        sdict['vhdpath'] = request.POST['vhdpath'].strip()
        model.objects.update_or_create(vhdname=sdict['vhdname'],defaults=sdict)
        return HttpResponse(json.dumps({'sts':"修改成功"}))

    if request.POST['posttype'].strip() == 'del': #delete infors.
        datas_del = request.POST.getlist('datas_del')
        for i in datas_del:
            item = model.objects.get(pk=i)
            time.sleep(0.1)
            item.delete()
        return HttpResponse(json.dumps({'sts':"删除成功"}))
        
    context={'obj_list':obj_list,'counts':counts}
    template_name = 'sinfors/vmmgmt_%s.html'  % model.__name__.lower()  # 每个Python的类都有一个 __name__ 属性返回类名。 这特性在当我们直到运行时刻才知道对象类型的这种情况下很有用。 比如, hvvms 类的 __name__ 就是字符串 'hvvms' 。
    #return render_to_response(template_name,context) #无法接收csrfmiddretoken参数
    return render(request,template_name,context)

参考:http://djangobook.py3k.cn/2.0/chapter08/  method_splitter(request, *args, **kwargs)

 

posted on 2016-06-17 14:51  momingliu11  阅读(711)  评论(0编辑  收藏  举报