zoukankan      html  css  js  c++  java
  • Django FBV and CBV

    Django FBV andCBV

    FBV_CBV

    FBV 就是函数 :function
    CBV 就是类 : Class

    urls.py

    url(r'cbv_index', views.CBV.as_view())    #这样就是去访问 views.py 里面的类
    

    models.py

    improt json    # json格式转换,需要引用
    from django.views improt View    # 加载这个类
    
    class CBV(View):    # 使用时,必须继承 View 类
        def get(self,request):
            #self.dispatch    ->  看源码是如何操作的
            pass
        
        def post(self,request):
            pass
    

    写一个类继承VIEW 调用View 的dispath 函数之前做一个 session验证

    要注意俩点:

    1:用的 CBV 的话 需要导入 from django.utils.decorators import method_decorator 之后@method_decorator(auth)放在函数名上, 如果放在类上需要加个参数 @method_decorator(auth,name='get') ,说明是 给 get函数使用

    2:但是django有个BUG 装饰器方法都会出现 CSRF问题 ,所以需要写一个dispath方法 直接调用VIEW里面的 dispath 进行反射@method_decorator(auth) 放在 dispath上面

    serializers序列化

    improt json
    ditc1 = {'tag':None,'data':None, 'status': Ture }
    
    ret_data = json.dumps(ditc1)   # 把字典转换为字符串 返回
    return HttpResponse(ret_data) 
    

    还有一种格式
    QuerySet_list的对象,它对象的点 就是QuerySet对象
    如果是QuerySet_List就需要先把它转换成 QuerySet再使用

    user_obj.first()#如果这样放入字典里再返回 就会报错!

    from django.core import serializers

    serializers工具可以将queryset转换成json格式返回给前端

    这样使用 :serializers.serialize('json', user_obj)

    json_data = serializers.serialize('json', user_obj)
    
    dict1['data'] = json_data
    
    request.session['login']=user_obj.first().Name
    
    return HttpResponse(json.dumps(dict1))


    Django CBV 实现登录验证

    urls.py

    from hc import views
    urlpatterns = [
        url(r'del_session/', views.del_session),
        url(r'login_demo/', views.Login.as_view()),
        url(r'index/', views.Index.as_view()),
        # r'....' , views.[Class].as_view()  方法
    ]
    

    CBV 实现登录验证

    views.py

    from django.views import View
    import json
    
    #FBV
    def del_session(request):
        request.session.clear()        
        #清除session ,服务端的session删除了,客户端再用原来的cookie来验证,找不到它就失效了。
        get_session = request.session.get('login',123)
        return HttpResponse(json.dumps(get_session))
    
    
    #CBV
    class Auth(View):      # 需要判断是否有session信息可以继承类来判断
        def dispatch(self, request, *args, **kwargs):
            if request.session.get('login', False):    # 判断 session的值是不是login
                response = super(Auth, self).dispatch(request,  *args, **kwargs) 
                # super() 函数是用于调用父类(超类)的一个方法
                # print(response)
                return response
            else :       # 没有这个session 就跳去login
                return redirect('/login_demo')
    
    
    class Index(Auth):   #继承了这个Auth 类来判断用户的 session
        def get(self, request):
            # print (request.session)
            return HttpResponse('登录成功,欢迎使用本系统!')
    
    
    class Login(View):
        def get(self,request):           # 请求为GET 时 会直接跳转到登录页面
            return render(request, 'login.html')
    
        def post(self, request):      # 请求为 POST 时,判断用户提交的表单
            username = request.POST.get('username', False)   
               # 当 username 取不到返回取值就为 False
            password = request.POST.get('password', False)   
               # 当 password 取不到返回取值就为 False
            if not username or not password:
                return HttpResponse('输入不能为空!')
            else:  # 查询数据库 并判断是否成功
                user_obj = models.UserInfo.objects.filter(
                    username=username,
                    password=password
                )   #这里取不到数据库的内容就是 为False ,上面定义的
                if user_obj.first():    #登录成功
                    # print(user_obj.first().name)
                    request.session['login'] = user_obj.first().name   
                    #写入session信息。这里的 login要和 del session 的一致
                    #  这里的session 相当于一个字典,把对应的key传入对应的值
                    # print (request.session['login'])
                    # print ('----------------------')
                    # print (request.session.get('login'))
                    return redirect('/index')
                else :
                    return HttpResponse('用户名或密码错误!')



    总结

    CBV
    本质,基于反射来实现的
    流程,路由,as_view() -> 内部源码view里面的dispatch方法 -> 反射执行
    取消csrf_token认证。
    针对于类里面的dispatch方法上面加入装饰器
    @csrf_protect # 需要验证csrf_token认证
    @csrf_exempt # 免除csrf_token认证

    针对于类上面使用加入装饰器
    @method_decorator(csrf_exempt, name='dispatch') # 加在类上面
    class Xxxx(view):

    CBV 的知识点
    如果在CBV里面加装饰器需要导入一个包
    from django.urils.decorators import method_decorator # 在CBV里加装饰器需要导入的包
    - @method_decorator(csrf_exempt) #在dispatch 方法中使用
    - @method_decorator(csrf_exempt, name='dispatch') # 加在类上面

    @method_decorator(csrf_exempt) # 加载类方法上面
    def dispatch(self, request, *args, **kwargs):
    return super(Mydispatch, self).disptch(request, *args, **kwargs)


    @method_decorator(csrf_exempt, name='dispatch') # 加在类上面
    class Xxxx(view):


    扩展知识:
    -csrf
    基于中间件的process_view方法
    装饰器给单独函数进行设置(认证或者无需认证)

  • 相关阅读:
    Eclipse Alt + / 快捷键失效
    oracle nvl()函数
    搭建spring boot项目
    Maximum call stack size exceeded
    vue混入函数问题
    ASP.NET Core 2.0中的Azure Blob存储
    如何在ASP.NET Core 2.0中使用Razor页面
    将参数传递给ASP.NET Core 2.0中的中间件
    使用.net core在Ubuntu构建一个TCP服务器
    如何在ASP.NET Core Web API测试中使用Postman
  • 原文地址:https://www.cnblogs.com/huidou/p/10757897.html
Copyright © 2011-2022 走看看