django 请求周期 与 cbv fbv

1.生成请求头 请求体信息 发送http请求
2.服务器解析根据请求头url的信息 url路径分发(自上而下) 
3.匹配成功执行,执行指定的views函数
URL --> 函数    FBV
URL --> 类      CBV
根据请求头中的request.method进行自动自行方法(POST,GET)

4.业务处理
- 根据个人需求自定
- 操作数据库
- 原生mysql
- ORM 
返回用户结果:
- 响应内容
-相应头
- 相应体

CBA:

继承父类Views
类中实现找到请求头method中 判断post get 方式 返回相应函数
重写父类 display 方法  每次调用都会执行这个方法 dispatch内部执行反射方法 判断请求 返回相应的函数

自带:'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

def fbv(request):
    if request.method == 'GET':
        return HttpResponse('FBV.GET')
    elif request.method == 'POST':
        return HttpResponse('FBV.POST')


from django.views import View
class CBV(View):

    def dispatch(self, request, *args, **kwargs):
        print('dispath')
        result = super(CBV,self).dispatch(request,*args,**kwargs)
        return result
        # 'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    def get(self,request):
        # return HttpResponse('CBV.GET')
        return render(request,'cba.html')

    def post(self,request):
        print(request.body)   # b'user=kk'

        ret = HttpResponse('CBV.POST')
        ret['a1'] = 'b1'
        ret.set_cookie('c1','c2')
        """
        响应头:
            a1=b1
            cookies: c1=c2
        体:
            CBC.POST 
        """
        return ret







猜你喜欢

转载自blog.csdn.net/weixin_42100915/article/details/80680246
今日推荐