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=)
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>
cbv_login.html
使用url访问默认是get方式,显示cbv_login.html页面,提交页面,进入post页面,显示cbv_post数据
get还是post,是由于请求头中的Request Method:获取,从而找到对应方法。使用反射查找,来执行对应方法。
.由Request URL请求去获取路径,与urls进行匹配,找到对应的类
.由请求体得到:Request Method:GET
.获得类中方法
方法名 = 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:
Content-Type:text/html; charset=utf-
Date:Wed, Mar :: GMT
h1:v1
Server:WSGIServer/0.1 Python/2.7.
Set-Cookie:c2=v2; Path=/
Set-Cookie:c1=v1; Path=/
X-Frame-Options:SAMEORIGIN
'''
return ret
python---django请求-响应的生命周期(FBV和CBV含义)的更多相关文章
- python 全栈开发,Day84(django请求生命周期,FBV和CBV,ORM拾遗,Git)
一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...
- django请求生命周期,FBV和CBV,ORM拾遗,Git
一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...
- python+requests 请求响应文本出错返回“登录超时”
Python+requests请求响应:"msg":"登录过时" 1.出错原代码: import requests import json#页面按条件搜索返回相 ...
- python Django请求生命周期
首先我们知道HTTP请求及服务端响应中传输的所有数据都是字符串. 在Django中,当我们访问一个的url时,会通过路由匹配进入相应的html网页中. Django的请求生命周期是指当用户在浏览器上输 ...
- ASP.NET MVC5请求管道和生命周期
请求处理管道 请求管道是一些用于处理HTTP请求的模块组合,在ASP.NET中,请求管道有两个核心组件:IHttpModule和IHttpHandler.所有的HTTP请求都会进入IHttpHandl ...
- Django请求响应对象
请求与响应对象 HttpRequest HttpRequest存储了客户请求的相关参数和一些查询方法. path 请求页面的全路径,不包括域名-例如, "/hello/". met ...
- DRF对Django请求响应做了技术升级
Django视图是用来处理请求和响应的,Django默认是按Form和Template来设计的,如果要处理以JSON格式为主的RESTful API,那么就需要对Django请求和响应的处理代码进行优 ...
- jsp学习(1)jsp请求过程和生命周期
一.服务器处理jsp请求的过程: 以下步骤表明了 Web 服务器是如何使用JSP来创建网页的: 1.浏览器发送一个 HTTP 请求给服务器. 2.Web 服务器识别出这是一个对 JSP 网页的请求,并 ...
- Vue系列(二):发送Ajax、JSONP请求、Vue生命周期及实例属性和方法、自定义指令与过渡
上一篇:Vue系列(一):简介.起步.常用指令.事件和属性.模板.过滤器 一. 发送AJAX请求 1. 简介 vue本身不支持发送AJAX请求,需要使用vue-resource.axios等插件实现 ...
随机推荐
- Visual Studio控制台程序输出窗口一闪而过的解决方法
转载大牛的博客,自己也遇到了类似的问题,解决方法很详细,也很管用 刚接触 Visual Studio的时候大多数人会写个Hello World的程序试一下,有的人会发现执行结束后输出窗口会一闪而过 ...
- docker之搭建私有仓库
一.私有仓库 1.防止网络原因:下载慢,访问不到的情况,需要在内网搭建一个私有仓库. 二.仓库镜像下载 [root@node03 ~]# docker pull registry 三.创建私有仓库容器 ...
- 软件测试_Loadrunner_APP测试_性能测试_脚本优化_脚本回放
本文主要写一下在使用Loadrunner录制完毕APP脚本之后如何对脚本进行回放,如有不足,欢迎评论补充. 如没有安装Loadrunner软件,请查看链接:软件测试_测试工具_LoadRunner: ...
- VC++ 屏蔽掉警告
使用VC6.0在开发程序的时候经常会遇到很多警告,很麻烦,也很耽误时间,可以使用如下方法屏蔽掉警告 在StdAfx.h 中 #define VC_EXTRALEAN 下面增加:#pragma warn ...
- 主流蓝牙芯片盘点,Nordic/TI/博通哪家强?
无线通信技术自19世纪中期诞生以来,从使用狼烟.火炬.闪光镜.信号弹等在视距内传输信息,到1838年塞缪尔・莫尔斯发明电报网,再到电报网被电话取代,再到几十年后的1895年马可尼首次从英国怀特岛到30 ...
- 第二个Sprint
能够实现三个数,两个操作符的四则运算.
- 解决eclipse中mybatis的xml配置文件无代码提示问题
https://blog.csdn.net/IRainReally/article/details/81743506
- Spring IOC AOP的原理 如果让你自己设计IOC,AOP如何处理(百度)
百度的面试官问,如果让你自己设计一个IOC,和AOP,如何设计, 我把IOC的过程答出来了,但是明显不对, (1) IOC 利用了反射,自己有个id,classtype,hashmap,所有的功能都在 ...
- 扩展名为DBF的是什么文件啊?
扩展名为DBF的文件: .dbf文件是dBase和FoxPro所使用的数据库格式,在没有这两种软件的情况下,可以使用Excel打开文件.在Excel的“打开”文件的对话框中,选择文件类型为“dBase ...
- 从0在windows上一次性上传本地整个项目(包含所有文件/文件夹)到 Github
1.注册并登陆Github. 2.登陆进去之后的页面,点击这个“库”,这表示你在Github上上的代码仓库,我这里已经创建过一个了,所以数量是1 3.在仓库选项卡中,点击“新建”按钮添加一个项目. 4 ...