python---django请求-响应的生命周期(FBV和CBV含义)
Posted 山上有风景
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python---django请求-响应的生命周期(FBV和CBV含义)相关的知识,希望对你有一定的参考价值。
Django请求的生命周期是指:当用户在访问该url路径是,在服务器Django后台都发生了什么。
客户端发送Http请求给服务端,Http请求是一堆字符串,其内容是:
访问:http://crm.oldboy.com:8080/login.html,客户端发送Http请求
1.路由映射,匹配路由(从上到下,匹配到就停止),对应相应views中的业务函数
url(r\'^login.html\', views.login),
2.匹配成功后,执行views下的对应函数:(FBV)
def login(req): print(\'req.body\',req.body) print("GET",req.GET) message=\'\' if req.method == "POST": print(req.body) print(req.POST) user = req.POST.get("username") pwd = req.POST.get("password") count = models.Administrator.objects.filter(username=user,password=pwd).count() if count: red = redirect("/index.html") timeout = datetime.datetime.now()+datetime.timedelta(seconds=3) red.set_cookie(\'username\',user,expires=timeout) return red else: message = "用户名或密码错误" return render(req,"login.html",{\'msg\':message})
URL --> 函数 ====> FBV(Function-based views) 基于函数的视图
URL --> 类 ====> CBV (Class-based views) 基于类的视图
FBV:在Django中使用较多,在其他框架中多使用CBV,例如tornado,还有PHP的多种框架等
Django中CBV使用:
首先需要设置views中的类:
from django.views import View class CBV(View):
#根据请求头中的request method进行自动执行get和post def get(self,request): return render(request,"cbv_login.html") def post(self,request): return HttpResponse("<h1>cbv_post</h1>")
然后修改urls文件路由:
urlpatterns = [ url(r"cbv",views.CBV.as_view()) ]
模板文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/cbv" method="post"> {% csrf_token %} <div> <label for="user">用户名:</label> <input type="text" id="user" name="username"/> </div> <div> <label for="pwd">密码:</label> <input type="password" id="pwd" name="password"/> </div> <div> <label></label> <input type="submit" value="登录"> <label>{{ msg }}</label> </div> </form> </body> </html>
使用url访问默认是get方式,显示cbv_login.html页面,提交页面,进入post页面,显示cbv_post数据
get还是post,是由于请求头中的Request Method:获取,从而找到对应方法。使用反射查找,来执行对应方法。
1.由Request URL请求去获取路径,与urls进行匹配,找到对应的类 2.由请求体得到:Request Method:GET 3.获得类中方法 方法名 = getattr(对象,"GET") 方法名() #执行对应函数
源码查看:
@classonlymethod def as_view(cls, **initkwargs): """ Main entry point for a request-response process.请求-响应的主入口点,在url解析时调用 """ for key in initkwargs: #cls.http_method_names: #[u\'get\', u\'post\', u\'put\', u\'patch\', u\'delete\', u\'head\', u\'options\', u\'trace\'] if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don\'t do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) #print(cls) #<class \'app1.views.CBV\'> def view(request, *args, **kwargs): self = cls(**initkwargs) #实例化CBV对象 if hasattr(self, \'get\') and not hasattr(self, \'head\'): self.head = self.get self.request = request #print(request) <WSGIRequest: GET \'/cbv\'> #print(request.method) GET self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs)#调用dispatch方法,将<WSGIRequest: GET \'/cbv\'>传入 view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn\'t exist, # defer to the error handler. Also defer to the error handler if the # request method isn\'t on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) #去调用对应的函数 else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)
推荐:介绍——基于类的视图(class-based view)
3.业务处理
-----根据个人需求自定义
-----对于框架:基本操作是操作数据库
---pymysql (原生)
---SQLAlchemy
---Django中orm
-----响应内容:返回给用户的结果:响应头和响应体
我们写的HTTPResponse是写在响应体中
响应头的定制:
def post(self,request): ret = HttpResponse("<h1>post</h1>")
#下面为设置请求头 ret[\'h1\'] =\'v1\' ret.set_cookie(\'c1\',\'v1\') ret.set_cookie(\'c2\',\'v2\') \'\'\' 响应头:h1=v1 cookies:c1=v1;c2=v2 响应体:<h1>post</h1> 请求头信息: Content-Length:13 Content-Type:text/html; charset=utf-8 Date:Wed, 28 Mar 2018 13:54:53 GMT h1:v1 Server:WSGIServer/0.1 Python/2.7.10 Set-Cookie:c2=v2; Path=/ Set-Cookie:c1=v1; Path=/ X-Frame-Options:SAMEORIGIN \'\'\' return ret
以上是关于python---django请求-响应的生命周期(FBV和CBV含义)的主要内容,如果未能解决你的问题,请参考以下文章
Python Django 生命周期 中间键 csrf跨站请求伪造 auth认证模块 settings功能插拔式源码