django视图层

三板斧

HttpResponse

返回字符串类型

Render

返回html页面,并且在返回给浏览器之前还可以给html文件传值

  • 内部原理简介
from django.template import Template,Context
res = Template('<h1>{{ user }}</h1>')
con = Context({'user':{'username':'jason','password':123}})
ret = res.render(con)
print(ret)
return HttpResponsel(ret)

Redirect

重定向

总结

视图函数必须要返回一个HttpResponse对象!!!

JsonResponse对象

老生常谈 --- json格式的数据有什么用

不同编程语言之间的数据交互

JsonResponse对象如何使用

  • 后端数据通过JsonResponse传给前端
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
import json
# Create your views here.
def ab_json(request):
    user_dic = {'name':'鬼鬼','password':'1026'}
    
    # json模块方法
    '''
    js_str = json.dumps(user_dic,ensure_ascii=False)
    return HttpResponse(js_str)
    '''

    # JsonResponse方式 --- 通过源码掌握用法
    return JsonResponse(user_dic,json_dumps_params={'ensure_ascii':False})
  • 注意

JsonResponse默认只能序列化字典,序列化其他数据格式需要加safe参数

- 网页报错信息
In order to allow non-dict objects to be serialized set the safe parameter to False.
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
import json
# Create your views here.
def ab_json(request):
    l = ['鬼鬼','叮当叮当']
    # JsonResponse方式 --- 通过源码掌握用法
    return JsonResponse(l,safe=False,json_dumps_params={'ensure_ascii':False})

form表单上传文件后端如何操作

form表单上传文件

  • method必须指定为post
  • enctype必须指定为formdata
def get_file(request):
    if request.method == 'POST':
        # 后端获取文件数据
        print(request.FILES)
        # 后端获取文件对象
        file_obj = request.FILES.get('file')
        # 获取文件名称
        print(file_obj.name)
        # 保存前端传过来的文件
        with open(file_obj.name,'wb') as f:
            for line in file_obj.chunks():
                f.write(line)
        return HttpResponse('文件保存成功')
    return render(request,'form.html')

request对象方法

# 后端获取文件数据
print(request.FILES)
# 原生浏览器发过来的二进制数据
print(request.body)
# 获取url
print(request.path)
# 获取完整的url及问号后面的参数
print(request.get_full_path())

FBV与CBV

简介

视图函数既可以是函数也可以是类

FBV(function base views)

就是在视图里使用函数处理请求,在之前django的学习中,一直使用的方式

CBV(class base views)

CBV基本使用

就是在视图里使用类处理请求

Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:

  1. 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  2. 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
from django.views import View


class MyLog(View):
    def get(self,request):
        return render(request,'form.html')
    def post(self,request):
        return HttpResponse('我是POST')
   


url(r'^class/',views.MyLog.as_view()),
    
# CBV特点:能够直接根据请求方式的不同直接匹配到对应的方法执行

CBV 内部源码是如何实现的 --- 查看源码分析

  • 突破口
url(r'^class/',views.MyLog.as_view()),
# url(r'^class/',views.view),

CBV与FBV在路由匹配中本质是一样的,都是路由对应函数内存地址

as_view加小括号可以运行,所以猜测是类的方法,通过看源码发现as_view是被@classmethod修饰的类方法

    @classonlymethod
    def as_view(cls, **initkwargs):
        """
        Main entry point for a request-response process.
        """
        ...

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            # cls是自己定义的类,self是自定义的类缠身的对象
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            ...
            return self.dispatch(request, *args, **kwargs)
        ...
        return view
    
    
	# CBV的精髓
    '''
    获取当前请求的小写格式,然后对比当前请求方式是否合法
    通过反射getattr(通过字符串操作对象的属性或者方法)
    handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    第一个参数:自己写的类产生的对象
    第二个参数:请求方式,比如get
    第三个参数:当找不到第二个参数对应的属性或者方法就会使用第三个参数
    handler= 自定义类的get方法
    '''
    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)
posted @ 2020-06-01 20:20  微信搜索-程序媛小庄  阅读(234)  评论(0编辑  收藏  举报