视图层详解,cbv和fbv,文件上传

一.复习

二.视图层之请求对象

三.视图层之响应对象

### 重点:JsonResponse的使用(看源码)
from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse

def index(request):
	#三件套
	# return HttpResponse(ok)
	# return render(request,index.html,context={name:lqz,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,22,13,lqz,[1,2,3],{
          
   name:lqz,age:19}],safe=False)

补充知识之json序列化与反序列化

import json
# 数字,字符串,布尔,None,字典,列表都可以使用json序列化和反序列化
# 序列化
a = None
b = False
print(json.dumps(a))  # null
print(json.dumps(b))  # false

ll=[11,12,13,lqz]
res = json.dumps(ll)
print(res)  # [11,12,13,"lqz"]
print(type(res))  # <class str>

# 反序列化
c = false
print(json.loads(c)) # False

四.cbv和fbv

# cbv基于类的视图(class base view)和fbv基于函数的视图(function base view)
# 之前学的全是fbv,写的是视图函数

# 写视图类(还是写在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

五.文件上传

## 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(文件上传成功)

六.postman软件

模拟发送http请求(控制请求路径,请求方式,请求头,请求体)

七.form表单,提交地址

# action
#1 不写,默认向当前地址发送请求
#2 /index/,向当前域(http://127.0.0.1:8000/)的/index/发送请求
#3 http://127.0.0.1:8000/index/,向该地址发送请求(可以向第三方服务发送请求)

# method
#1 post:发送post请求(默认编码情况下:以key=value&key=value的形式拼到请求体中)
#2 get:发送get请求(以key=value&key=value的形式拼到路径中)
<form action="/index/" method="post">
	<p>用户名: <input type="text" name="name"></p>
	<p>密码: <input type="text" name="password"></p>
	<p><input type="submit" value="提交"></p>
</form>

八.Pycharm的自动提示

from django.core.handlers.wsgi import WSGIRequest
# pycharm的自动提示
request=request # type:WSGIRequest
经验分享 程序员 微信小程序 职场和发展