django-视图
1 MVC
m:model
v:view 视图 HTML文件
c:controller 控制器
2 MTV
m:model
t:template 模板 HTML文件
v:view 视图 负责业务逻辑 FBV CBV
url分发器
3 逻辑
接收一个请求,返回一个响应
4 请求(request)
request.method 请求方式
request.GET url携带的参数
request.POST POST请求发送的数据
request.body 请求数据 请求体
request.FILE 上传文件 form添加 enctype = "multipart/form-data"
request.META 请求头的信息
request.path_info 路径信息 不包含IP和端口 不包含参数
request.get_full_path() 路径信息 不包含IP和端口 包含参数
request.COOKIES 获取cookie
request.session 获取session
request.is_ajax() 是否是ajax请求
request.is_secure() http false https true
5 响应(response)
HttpResponse('字符串') content-type:'txt/html'
render(request,'xx.html',{'k1':'v1'}) 返回一个完整的html页面
redirect('url') 重定向 本质:Location:url 再次发送一个get请求
JsonResponse({'code':v1}) content-type:'application/json'
TemplateResponse(request,'xx.html',{'k1':'v1'})
6 CBV
定义:
from django.views import View
class AddView(View):
def get(self,request,*args,**kwargs):
# 处理get请求逻辑
return response
def post(self,request,*args,**kwargs):
# 处理post请求逻辑
return response
def dispatch(self,request,*args,**kwargs):
ret = super().dispatch(request,*args,**kwargs):
return ret
使用:
url(r'add/',view.AddView.as_view())
使用了反射原理
7 加装饰器
FBV 直接加
CBV 需要导入模块
from django.utils.decorators import method_decorator
1 加在方法上
@method_decorator(装饰器名)
def get(self,request,*args,**kwargs):pass
2 加在dispatch
@method_decorator(装饰器名)
def dispatch(self,request,*args,**kwargs):pass
3 加在类上
@method_decorator(装饰器名,name='get')
class AddView(View):
注意点:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
csrf_exempt 只能加载dispatch才能生效

浙公网安备 33010602011771号