Django——视图层(请求&响应对象,cbv和fbv,文件上传)

一、视图层之请求对象

def index(request):
    '''
    request:django封装的对象,它的类是WSGIRequest,它里面包含了所有http请求的东西
    '''
    print(request)
    print(type(request))
    # from django.core.handlers.wsgi import WSGIRequest
    #######################1 看前博客
    print(request.method)
    print(request.GET)
    print(request.POST)

    ########################2 path里的,get_full_path,META,FIELS,body
    # 自定制请求头
    # 上传文件使用的编码方式是form-data,默认编码方式urlencoded
    print(request.is_ajax()) # 是不是ajax请求
    print(request.path)      # 请求路径
    print(request.get_full_path()) # 请求全路径,带数据

    # print(request.body)      # 请求体,二进制,如果传文件,这个报错
    '''
    使用form表单,默认情况下数据被转成name=lqz&password=123放到请求体中
    request.POST其实是从body中取出bytes格式的,转成了字典
    requet.GET其实是把路径中?后面的部分拆出来,转成了字典
    '''
    print(request.encoding) # 客户端向服务端传递时,使用的编码方法

    print(request.META)    # 重点,字典,一堆东西,请求用户的ip地址,请求头中数据,用户自定制请求头的数据
    '''
    把请求头的key值部分统一加HTTP_  并且全部转成大写
    '''
    print(request.META['REMOTE_ADDR'])  # 客户端的ip地址
    print(request.FILES)  # 客户端上传的文件



    ########################3 暂时不用关注(后面会详解)
    print(request.COOKIES) # 空字典
    print(request.session) # session对象
    print(request.user)    # 匿名用户
    return HttpResponse('ok')

http请求头,请求编码格式3种

urlencoded
form-data
jason

二、视图层之响应对象

### 重点:JsonResponse的使用(看源码)

def index(request):
    # 三件套
    # return HttpResponse('ok')
    # return render(request,'index.html',context={'name':'lili','age':18})
    # return redirect('/home') # 重定向自己的地址,重定向第三方地址,经常跟反向解析一起使用

    # 向客户端返回json格式数据
    # import json
    # res=json.dumps({'name':'张三','age':18},ensure_ascii=False)
    # return HttpResponse(res)
    # django内置提供的JsonResponse
    # 本质还是HttpResponse

    # ensure_ascii
    # return JsonResponse({'name':'张三','age':18},json_dumps_params={'ensure_ascii':False})
    # safe,转换除字典以外的格式,需要safe=False
    return JsonResponse([11,12,13,'lili',[1,2,3],{'name':'lili','age':19}],safe=False)

http响应头 编码

content-type:text/html; charset=utf-8   # 返回数据的编码类型

容易混淆: enctype编码格式(把数据以什么格式放到一起)不是字符编码

三、cbv和fbv

CBV基于类的视图(Class base view)和FBV基于函数的视图(Function base view)

# 写视图类(还是写在views.py中)
## 第一步,写一个类,继承View
from django.views import View

class Index(View):
    def get(self, request):  # 当url匹配成功,get请求,会执行它
        return HttpResponse('ok')

    def post(self,request):
        return HttpResponse('post')
    
## 第二步:配置路由
path('index/', views.Index.as_view()),

# 前期,全是FBV,后期,drf全是CBV

四、cbv本质

# 1 请求来了,路由匹配成功执行 path('index/', views.Index.as_view()),
    执行views.Index.as_view()()
# 2 本质是执行as_view()内部有个闭包函数view()
# 3 本质是view()---》dispatch()
# 4 dispatch内部,根据请求的方法(get,post)---->执行视图类中的def get  def post

五、简单文件上传

# html注意编码方式
<form action="/index/" method="post" enctype="multipart/form-data">

    <p>用户名:<input type="text" name="name"></p>
    <p>密码:<input type="password" name="password"></p>
    <p><input type="file" name="myfile"></p>
    <p><input type="submit" value="提交"></p>
</form>

# views.py
def index(request):
    file=request.FILES.get('myfile')
    # 打开一个空文件,写入
    with open(file.name,'wb') as f:
        for line in file.chunks():
            f.write(line)
    return HttpResponse('文件上传成功')
原文地址:https://www.cnblogs.com/guojieying/p/13784357.html