python自动化运维学习第二十五天--FBV、CBV和序列化

FBV:function base views (views中使用函数来接收路由)
CBV:class base views(views中使用class来接收路由)
前几篇文章中都是使用的FBV,下面使用CBV处理路由请求
views.py部分代码

from django.views import View                     #导入View模块
class Cbv(View):                                  #定义Cbv类继承自View
    def get(self,request):                        #接收get请求
        return render(request,"index.html")

    def post(self,request):                       #接收post请求
        user = request.POST.get("user", False)
        password = request.POST.get("pwd", False)
        users_list = models.UserInfo.objects.all()
        if not user or not password:
            return render(request, "index.html", {"isnot":'yes'})
        for item in users_list:
            if user == item.username and password == item.password:
                return redirect("/page/")
        return render(request, "index.html", {"isexists":"false"})

urls.py部分代码

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^page/', views.page),
    url(r'^index/', views.Cbv.as_view()),      #Cbv是views中的定义的继承自View的类,as_view()是固定写法
]

index.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>

<form action="/index/" method="post">
    用户名:<input type="text" name="user">
    密码:<input type="password" name="pwd">
    <input type="submit" value="登录">
    {% if isnot == "yes" %}
    <p>用户名或密码不能为空!</p>
    {% endif %}

    {% if isexists == "false" %}
    <p>用户名或密码错误,请重新输入!</p>
    {% endif %}
</form>

</body>
</html>
序列化

在views中,有些场景需要使用HttpResponse来返回数据,如果返回的数据是dic类型,可以使用json.dumps()方法把dic类型转换为string类型,通过HttpResponse返回

import json
def test(request):
    dic = {"data":"test data","user":"zhangsan"}
    return HttpResponse(json.dumps(dic))           #使用json.dumps()方法把dic类型转换为string类型

如果返回的是数据库查询的QuerySet或者QuerySetList类型数据,直接使用json.dumps()方法转换就会报错。这时就要使用序列化serializers

from django.core import serializers               #导入serializers模块
def test(request):
    dic = {"data":"test data","user":"zhangsan"}
    user_obj = models.UserInfo.objects.filter(name="张三")
    user_json = serializers.serialize("json",user_obj)             #把queryset序列化为json
    dic["data"] = user_json
    return  HttpResponse(json.dumps(dic))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值