The life cycle of a Django request is what happens when a user accesses the URL path that is in the server Django daemon.
The client sends an HTTP request to the server, and the HTTP request is a bunch of strings whose contents are:
Access: http://crm.oldboy.com:8080/login.html, client sends HTTP request
1. Route map, matching route (from top to bottom, match to stop), corresponding to the business function in the corresponding views
URL (r'^login.html', Views.login),
2. After the successful match, execute the corresponding function under Views:(FBV)
def login (req): Print ('Req.body', Req.body) print ("GET", req. GET) Message="' ifReq.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 ()ifcount:red= Redirect ("/index.html") Timeout= Datetime.datetime.now () +datetime.timedelta (seconds=3) Red.set_cookie ('username', user,expires=Timeout)returnRedElse: Message="incorrect user name or password" returnRender (req,"login.html",{'msg': Message})
View Code
URL --function ====> FBV (function-based views) function-based view
URL --Class ====> CBV (class-based views) class-based view
FBV: Use more in Django, use CBV in other frameworks, such as tornado, multiple frameworks for PHP, etc.
In Django, CBV uses:
First you need to set the class in views:
from django.views Import View class CBV (View):
#根据请求头中的request method performs The Get and postgetautomatically(self,request): return render ( Request,"cbv_login.html") def Post (self,request): Return HttpResponse ("")
Then modify the URLs file route:
Urlpatterns = [ url (r"cbv", Views.) Cbv.as_view ())]
Template file:
<! DOCTYPE html>"en">"UTF-8"> <title>title</title>"/CBV"Method="Post"> {% Csrf_token%} <div> <label for="User"> User name:</label> <input type="text"Id="User"Name="username"/> </div> <div> <label for="pwd"> Password:</label> <input type="Password"Id="pwd"Name="Password"/> </div> <div> <label></label> <input type="Submit"Value="Login"> <label>{{msg}}</label> </div></form></body>cbv_login.htmlUse URL access by default is Get method, display cbv_login.html page, submit page, go to post page, display cbv_post data
Get or post is due to the request method in the header, which is obtained to find the corresponding methods. Use reflection Lookup to execute the corresponding method.
1 . Request URL to get path, match URLs, find corresponding class 2 received by the requester: request Method:get 3 Get class method name = GetAttr (object,"get") method name () # Execute the corresponding function
Source view:
@classonlymethod def as_view (CLS,**Initkwargs):""" Main entry point for a request-response process. Request-Response main entry points, called at URL resolution""" forKeyinchInitkwargs: #cls. Http_method_names: #[u ' Get ', u ' post ', U ' put ', u ' patch ', u ' delete ', U ' head ', U ' options ', U ' trace '] ifKeyinchcls.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__))ifNot hasattr (CLS, key): Raise TypeError ("%s () received an invalid keyword%r. As_view" "Only accepts arguments that is already" "attributes of the class."%(cls.__name__, key)) #print (CLS) # <class ' App1.views.CBV ' >def view (Request,*args, * *Kwargs): Self= CLS (**initkwargs) #实例化CBV对象ifHasattr (Self,'Get') and not hasattr (self,'Head'): Self.head= self.Getself.request=Request #print (request) <wsgirequest:get '/CBV ' > #print (request.method) GET Self.args=args Self.kwargs=Kwargsreturn Self.dispatch (Request, *args, **kwargs) #调用dispatch方法, will <wsgirequest:get '/CBV ' > incoming view.view_class=CLS View.view_initkwargs=Initkwargs # take name and DocString from classupdate_wrapper (view, CLS, updated=()) # and possible attributesSetby decorators # like Csrf_exempt fromDispatch update_wrapper (view, Cls.dispatch, assigned=()) returnView Def dispatch (self, request,*args, * *Kwargs): # Try to dispatch to the right method; ifA method doesn't exist,# defer to the error handler. Also defer to the error handlerifThe # request method isn'T on the approved list. ifRequest.method.lower ()inchself.http_method_names: handler = GetAttr (self, Request.method.lower (), self.http_method_not_allowed) #去调用对应的函数Else: Handler=self.http_method_not_allowedreturnHandler (request, *args, **kwargs)
Recommendation: Introduction--Class-based view (class-based view)
3. Business Processing
-----customized to individual needs
-----for Frames: The basic operation is to manipulate the database
---pymysql (native)
---SQLAlchemy
---Django in ORM
-----Response Content: Results returned to the User: response header and response body
The HttpResponse we write is written in the response body.
Customization of the response header:
def Post (self,request): Ret= HttpResponse ("")
#下面为设置请求头ret[ ' h1 '] = ' v1 ' ret.set_cookie (' C1 ', ' v1 ') ret.set_cookie (' C2 ', ' v2 ')" "Response Header: h1=v1 cookies:c1=v1;c2=v2 Response Body:Request header information: Content-length: -Content-type:text/html; charset=utf-8date:wed, -Mar2018 -: Wu: -GMT h1:v1 server:wsgiserver/0.1python/2.7.TenSet-cookie:c2=v2; path=/Set-cookie:c1=v1; path=/X-frame-Options:sameorigin" " returnRet
Python---The lifecycle of the Django Request-response (FBV and CBV meanings)