Django视图层

三板斧

HttpResponse

"""
返回字符串类型
"""

 

render

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

 

redirect

"""
重定向
"""

 

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

# 视图函数必须要返回一个HttpResponse对象  正确  研究三者的原码即可得出结论

# render简单的内部原理
    from django.template import Template,Context
    res = Template('<h1>{{ user }}</h1>')
    con = Context({'user':           {'username':'jasosn','password':123}})
    ret = res.render(con)
    print(ret)
    return HttpResponse(ret)

 

JsonResponse对象

"""
json格式的数据有什么用?
    前后端数据交互需要使用到json作为过度 实现跨语言传输数据
    
前端序列化
    JSON.stringify()       json.dumps
    JSON.parse()           json.loads
    
"""


import json
from django.http import JsonResponse

def ab_json(request):
    user_dict = {'username': 'jason好帅哦', 'password': '123', 'hobby': 'girl'}

    l = [111,222,333,444,555,666]

    # 先转成json格式字符串
    # json_str = json.dumps(user_dict,ensure_ascii=False)
    # 将该字符串返回
    # return HttpResponse(json_str)
    # 读源码 掌握用法
    # return JsonResponse(user_dict, json_dumps_params={'ensure_ascii': False})
    return JsonResponse(l,safe=False)
    # 默认只能序列化字典 序列化其他需要加safe参数

 

form表单上传文件及后端如何获取

"""
********************************
form表单上传文件类型的数据            *
    1、method必须指定成post       *
    2、enctype必须换成formdata    *
********************************
"""

def ab_file(request):
    if request.method == 'POST':
        print(request.POST)  # 只能获取普通的键值对数据 文件不行
        print(request.FILES)  # 获取文件数据
        # <MultiValueDict: {'file': [<InMemoryUploadedFile: 8bb78c7b59a8662ac189cfae4a79ad67.jpg (image/jpeg)>]}>
        file_obj = request.FILES.get('file')  # 文件对象
        print(file_obj.name)

        # 保存
        with open(file_obj.name,'wb') as f:
            for line in file_obj.chunks():  # 推荐加上chunks方法 其实和不加是一样的 都是一行行的读取
                f.write(line)

    return render(request,'form.html')

 

request对象

"""
request.method
request.POST
request.GET
requset.FILES

补充:
request.path
request.path_info
request.get_full_path  # 能够获取完整的url及问号后面的参数
"""

print(request.path)  # /app01/ab_file/
print(request.path_info)  # /app01/ab_file/
print(request.get_full_path())   # /app01/ab_file/?username=jason

print(request.body)  # 原生的浏览器发过来的二进制数据

 

FBV与CBV(视图函数既可以是函数也可以是类)

FBV

"""
FBV(function base views) 基于函数的视图,就是在视图里使用函数处理请求。
"""

 

CBV

"""
CBV(class base views) 基于类的视图,就是在视图里使用类处理请求。
"""
# 视图函数既可以是函数也可以是类
def index(request):
    return HttpResponse('index')

# CBV

    from django.views import View

    class MyLogin(View):
           def get(self,request):
            return render(request,'form.html')

        def post(self,request):
            return HttpResponse('post方法')
    
    # CBV路由
    url(r'^login/',views.MyLogin.as_view())
    
  
"""
FBV和CBV各有千秋
CBV特点
    能够直接根据请求方式的不同直接匹配到对应的方法执行
"""

 

posted @ 2021-06-11 15:55  Palpitate~  阅读(25)  评论(0编辑  收藏  举报