djangoCBV、文件上传

1 request对象
method:请求方式
GET:get请求的参数(post请求,也可以携带参数)
POST:post请求的参数(本质是从bdoy中取出来,放到里面了)
COOKIES--->后面讲
META:字典(放着好多东西,前端传过来的,一定能从其中拿出来)
body:post提交的数据
path:请求的路径,不带参数
request.get_full_path() 请求路径,带参数

2 HttpResponse对象
-三件套
-JsonResponse:往前端返回json格式数据
-转列表格式:指定safe=False
-中文字符问题:json_dumps_params={‘ensure_ascii‘:False}

3 wsgiref,uwsgi,---都遵循wsgi协议
-遵循一个协议wsgi(Web Server Gateway Interface web服务网关接口)

4 CBV(基于类的视图)和FBV(基于函数的视图)
-cbv:一个路由写一个类
-先定义一个类:继承自View


from django.views import View class MyClass(View): # 当前端发get请求,会响应到这个函数 def get(self, request): return render(request,index.html) # 当前端发post请求,会响应到这个函数 def post(self,request): print(request.POST.get(name)) return HttpResponse(cbv--post)

View Code

-在路由层:
re_path(‘^myclass/$‘,views.MyClass.as_view()),

5 文件上传
-form表单默认提交的编码方式是enctype="application/x-www-form-urlencoded"
-前端:如果要form表单上传文件,必须指定编码方式为:multipart/form-data
-后端:


file=request.FILES.get(myfile) with open(file.name,wb) as f: for line in file: f.write(line) 

View Code

 

相关文章