zoukankan      html  css  js  c++  java
  • views 视图函数

    视图

    1. CBV和FBV
    
        FBV (function based view)
        CBV (class based view )
        
        CBV写法:
            from django.views import View
    
    
            class AddPublisher(View):
            
                def get(self, request):
                    print('这个是get')
                    return render(request, 'add_publisher.html')
    
                def post(self, request):
                    print('这个是post')
    
                    return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})
    
        使用:
            url(r'^add_publisher/', views.AddPublisher.as_view()),
    2. CBV简单的流程:
        1. AddPublisher.as_view() ——》 view函数
        2. 当请求到来的时候才执行view函数
            1. 实例化AddPublisher  ——》 self 
            2. self.request = request
            3. 执行self.dispatch(request, *args, **kwargs)
                1. 判断请求方式是否被允许
                    handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
                    通过反射获取对应的方法 
                    GET  ——》  get
                    POST ——》  post
                    
                2. 执行获取到的方法  get(request,)  或者post(request,)
                3. 得到HttpResponse对象,返回给self.dispatch
            4. 得到HttpResponse对象,返回django处理
        
    3. request
        request.method    ——》 请求的方式 8种  GET POST PUT DELETE OPTIONS
        request.GET		  ——》 字典  url上携带的参数
        request.POST	  ——》 字典  form表单通过POST请求提交的数据
        
        print(request,type(request))  #当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpRequest对象。Django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象。
    	print(request.method)		# 请求中使用的HTTP方法的字符串表示,全大写表示。
    	print(request.GET)          #包含所有HTTP  GET参数的类字典对象
    	print(request.POST)			# 包含所有HTTP POST参数的类字典对象
    	print(request.path_info)	# 返回用户访问url,不包括域名	
        print(request.body)			# 请求体,byte类型 request.POST的数据就是从body里面提取到的
        print(request.scheme)		# 表示请求方案的字符串(通常为http或https)
        print(request.get_host())	# ip 端口
        print(request.get_full_path())	# 返回包含参数(查询字符串)的url(不包括域名)
      request.FILES    # 上传的文件 4. response from django.shortcuts import render, HttpResponse ,redirect HttpResponse('字符串') —— 》浏览器显示字符串 render(request,'模板名字',{}) —— 》返回一个完整的页面 redirect(URL) —— 》跳转 重定向 location:url 5. JsonResponse JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。类似于HttpResponsed的使用方法
        from django.http import JsonResponse
    
    	ret = JsonResponse({'foo': 'bar'})
    	print(ret.content)
            return  ret
    
    	# b'{"foo": "bar"}'	        
    
    
    

      

    def json_data(request):
        date = {"name": 'alex', 'age': 84}
        import json
        return HttpResponse(json.dumps(date))  #content_type: application/json 
    
        return JsonResponse(date)   #content_type: application/text
    

      

    类型: content_type: application/json 如果是传递的是字符串 content_type: text /html;charset = utf - 8
    默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。 ret = JsonResponse([1, 2, 3], safe=False)
    6.装饰器的使用
    1. FBV的装饰器
    @装饰器

    2. CBV的装饰器:
    from django.utils.decorators import method_decorator


    1. 直接在方法上加:
    @method_decorator(wrapper)
    def get(self, request)

    2. 给dispatch方法加
    @method_decorator(wrapper)
    def dispatch(self, request, *args, **kwargs)

    3. 给类加
    @method_decorator(wrapper, name='post')
    @method_decorator(wrapper, name='get')
    class AddPublisher(View)
     
    # @method_decorator(wrapper, name='post') # 方法三:给类加,哪个方法用加哪个方法的名字
    # @method_decorator(wrapper, name='get')
    class AddPublisher(View):
    
        @method_decorator(wrapper)	# 方法二:给dispatch方法加
        def dispatch(self, request, *args, **kwargs):
            print('执行get方法之前')
            ret = super().dispatch(request, *args, **kwargs)
            print('执行get方法之后')
            return ret
    	@method_decorator(wrapper)   # 方法一:直接在方法上加
        def get(self, request):
            print('这个是get')
            # print(self.request)
            return render(self.request, 'add_publisher.html')
    
        def post(self, request):
            print('这个是post')
            print(request.body)
            err_msg = ''
            add_name = request.POST.get('new_name')
            pub_list = models.Publisher.objects.filter(name=add_name)
            if add_name and not pub_list:
                models.Publisher.objects.create(name=add_name)
                return redirect('/publisher/')
            if not add_name:
                err_msg = '不能为空'
            if pub_list:
                err_msg = '出版社已存在'
    
            return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})
    
    
    

      

    
    
  • 相关阅读:
    js--未来元素
    Nginx 浏览器打开是下载状态
    JS对象的深拷贝
    微信小程序--扫描二维码
    js--call( )/apply()/bind()--应用
    数学书籍
    【活动】你有创意我有奖!摹客X飞书2020产品设计大赛邀你来战
    APP设计实例解析,深色模式为什么突然就火了?
    焦虑求职季又至:2020UI设计师作品集如何准备?
    QQ音乐 vs 网易云音乐,用户体验哪家强?
  • 原文地址:https://www.cnblogs.com/perfey/p/9671354.html
Copyright © 2011-2022 走看看