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

views 视图函数

时间:2018-09-18 22:38:50      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:and   ddp   rtc   rom   object   objects   get   lis   提交   

视图

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: application/text 
默认只能传递字典类型,如果要传递非字典类型需要设置一下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})

  

views 视图函数

标签:and   ddp   rtc   rom   object   objects   get   lis   提交   

原文地址:https://www.cnblogs.com/perfey/p/9671354.html

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