FBV && CBV
FBV, CBV is a Django view routing model that, when a user requests a delivery of a routing system url, is forwarded to the views view to parse and process
FBV function base Views//CBV class base views
The difference is a direct use of function-driven, a class-driven, there are some differences in use
1) FBV
The URL is forwarded directly to one of the handler functions in the view based on the route match
Urlpatterns = [url (r ' ^home/', views.home),]
When a view function accepts a request, we are required to make a request for a category, by default, by a GET request
From django.shortcuts import httpresponsedef home (request): if Request.method = = "POST": Passreturn render (reque st, ' home.html ') if if Request.method = = "GET":p Assreturn render (request, ' home.html ')
2) CBV
The CBV route should correspond to the following form
Urlpatterns = [url (r ' ^home/', views. Home.as_view ()),]
View module to import the fixed view module and the home class to inherit the view
Form django.views import viewclass home (View): # The biggest benefit of custom CBV is the ability to do some of our custom actions before or after processing the request # dispatch is the Django process request method Equivalent to customizing the dispatch (the principle is through Reflection) def dispatch (self, request, *args, ** kwargs): printf (' Before ') # Calling the parent class method result = super (home, self). Dispatch (request, *args, **kwargs) printf (' after ') return result # here we don't need to judge the request type django automaticExecute the corresponding method def get (self,request): printf (REQUEST.METHOD) return render (request, ' home.html ') def post (self,request): print (REQUEST.METHOD) return render (request, ' home.html ')
HTTP request Processing
In the Django View module views, In addition to processing get, post requests, It is also possible to handle some other client data included in the HTTP request header, such as matching the client browser type;
Common requests that we handle
GET Request Request.get//POST Request request.post//process File upload Request. Files//handles multi-select Accept lists such as CheckBox Request.getlist//view request type Request.method//view request Source Address Request.path_info
Request. Files File Upload
Because of the Request. Files are very special, after the file upload, through the Django Request.POST.get () only the filename string, we can customize a file upload method
1) add enctype attribute to form form attribute
<form action= "/login/" method= "POST" enctype= "multipart/form-data" ></form><input type= "file" name= "a _file "></input>
2) Custom Upload in views
Import osobj = Request. Files.get ("a_file") printf (obj) # New upload storage file in Django working directory File_path = os.path.join (' upload ', obj.name) f = Open (obj.name , mode= "wb") # chunks () method is the one generator that Django internally handles file uploads responsible for chunking the data for I in Obj.chunks (): f.write (i) f.closer ()
Http_user_agent
Let's take ' http_user_agent ' for example to see how Django handles some of the useful data in the HTTP request header
The From DJANGO.CORE.HANDLERS.WSGI Import Wsgirequest # Request encapsulates all the requested information, but how do we get the data? def index (request): print (type request) print (request.environ) return render (request, ' index.html ')
The request has the data we want, the request is an instantiation of a class, so we can go to create his class inside to see, get
<class ' Django.core.handlers.wsgi.WSGIRequest ' >
Importing the Wsgireques module, it's easy to see the source code and find the Environ variable, which has the data we need to see
650) this.width=650; "src=" https://s3.51cto.com/wyfs02/M00/8E/84/wKiom1jCoxuDY3HzAAAZZIdT_dc490.png "title=" 1.png "alt=" Wkiom1jcoxudy3hzaaazzidt_dc490.png "/>
Print it out, Here's all the customer request Data.
650) this.width=650; "src=" https://s5.51cto.com/wyfs02/M00/8E/82/wKioL1jCoyvz66FnAACgnHVTdYk997.png "title=" 2.png "alt=" Wkiol1jcoyvz66fnaacgnhvtdyk997.png "/>
Find it, do it, and handle it accordingly.
From Django.core.handlers.wsgi import wsgirequestprintf (request) printf (' request.environ ') for k,v in Environ.items () printf (k,v) printf (request.environ[' http_user_agent ')
Cookies
Cookies are used to verify the identity of the user, and the cookie is used in Django to note the Cookie's access and settings, and the Salt's ability to encrypt the Cookie.
Set cookies
Adding cookie information when returning data to the client in a view function
def login (request): If request.method = = "POST": U = Request. Post.get (' username ') p = Request. Post.get (' pwd ') dic = user_info.get (u) if not dic:return render (request, ' login.html ') if dic[' pwd '] = = P:res = Redirect ('/index/')//or render (request ...) Res.set_cookie (' username111 ', u) return res
Once the user has successfully logged in, each subsequent visit will have a cookie request
650) this.width=650; "src=" https://s2.51cto.com/wyfs02/M02/8E/82/wKioL1jCo0yiaN5xAAJ3k5WUIPI713.png "title=" 3.png "alt=" Wkiol1jco0yian5xaaj3k5wuipi713.png "/>
Setting Cookie Parameters
Rep.set_cookie (key,value,...) Rep.set_signed_cookie (key,value,salt= ' Encryption ',...) parameter: key, Key value= ' ', value max_ age=none, Timeout period expires=None, timeout period (ie requires expires, so set it if hasn ' t Been already.) path= '/', cookie valid path,/ represents the root path, special: cookie with path can be accessed by any URL of the page Domain=none, cookie the domain name in effect Secure=false, &nbSp;https Transmission httponly=False only HTTP protocol transmission, cannot be obtained by JavaScript (not absolute, The underlying grab can be obtained or overwritten) response = render (request, ' index.html ') Response = redirect ('/index/')// set cookies, close browser invalidation response.set_cookie (' key ', ' value ')// Set cookie, n seconds only fail Response.set_cookie (' username111 ', "value", max_age=10)// set cookie, cutoff time fail Import datetimecurrent_date = datetime.datetime.utcnow () current_date = current_date + datetime.timedelta (seconds=5) response.set_cookie (' username111 ', "value", Expires=current_date) response.set _cookie (' username111 ', "value", max_age=10)
Get cookies
Request.get_signed_cookie (key, default=raise_error, salt= ", max_age=none) parameters: default: defaults salt: crypto salts Max_age: Background Control Expiration time
We can also use J s to control cookies to achieve a control page to customize the number of pages of the function
<div> <select id= "ps" onchange= "changepagesize (this)" > <option value= "ten" >10</option> <option value= ">30</option> " <option value= ">50</option> " <option value= ">100</option> </select></div><" div class= "pagination" > {{ page_str }}</div>// Operation of cookies directly in JS requires the use of the Jquery.cookie plugin <script src= "/static/jquery-1.12.4.js" ></script>< script src= "/static/jquery.cookie.js" ></script><script> $ (function ( ) { // path Control Cookie parameter effective page range &nBsp; var v = $.cookie (' per_page_count ', {' path ': "/user_ list/' "}); $ (' #ps '). val (v); function changepagesize (ths) { var v = $ (ths). val (); console.log (v) ; $.cookie (' per_page_count ', v, {' path ': "/user_list/" }); location.reload (); }</script>
User Login Verification
For FBV we can directly use the Python decorator for function decoration
def Auth (func): def inner (reqeust,*args,**kwargs): v = reqeust. Cookies.get (' username111 ') if not v:return redirect ('/login/') return func (reqeust, *args,**kwar Gs) return Inner @authdef index (reqeust): # Gets the currently logged-on user V = Reqeust. Cookies.get (' username111 ') return render (reqeust, ' index.html ', {' current_user ': V})
@method_decorator (auth,name= ' dispatch ') Class order ( name) using Ethod_decorator for decorating the control of the parameter representation Views. View): // can also operate inside the class # @method_decorator ( Auth) # def dispatch (self, request, *args, **kwargs): # return super (order,self). Dispatch (request, *args, **kwargs) // The method of decoration is generally not recommended # @ Method_decorator (auth) def get (self,reqeust): v = reqeust. Cookies.get (' username111 ') return render (reqeust, ' index.html ', {' current_user ': v}) def post (self,reqeust): v = reqeust. Cookies.get (' username111 ') return render (reqeust, ' index.html ', {' current_user ': v})
This article comes from the "change from every day" blog, so be sure to keep this source http://lilongzi.blog.51cto.com/5519072/1905302
Django Advanced operations for the automated Operations Python series