CBV and FBV
Version FBV:
# FBV Edition Add Class def add_class (Request): if Request.method = = ' POST' := Request. Post.get (' class_name ') models. Classes.objects.create (Name=class_name) return redirect ('/class_list/') return render (request, ' add_class.html ')
Version CBV:
#CBV Edition Add Class fromDjango.viewsImportViewclassaddclass (View):defGet (self,request):returnRender (Request,'add_class.html') defPost (self,request): Class_name= Request. Post.get ('class_name') models. Classes.objects.create (Name=class_name)returnredirect'/class_list/')
Attention:
When using CBV, the corresponding changes are also made in the urls.py:
# urls.py in the URL (r'^add_class/', views. Addclass.as_view ()),
Decorating the view with adorners FBV
The FBV itself is a function, so there is no difference between an adorner and a normal function:
defWrapper (func):defInner (*args,**Kwargs): Start_time=time.time () ret= Func (*args,**Kwargs) End_time=time.time ()Print(end_time-start_time)returnretreturnInner#FBV Edition Add Class@wrapperdefAdd_class (Request):ifRequest.method = ='POST': Class_name= Request. Post.get ('class_name') models. Classes.objects.create (Name=class_name)returnredirect'/class_list/') returnRender (Request,'add_class.html')
Decorating CBV with adorners
Django provides a method_decorator adorner for converting a function adorner to a method adorner.
#CBV Edition Add Class fromdjango.views impor View fromDjango.utils.decoratorsImportMethod_decoratorclassaddclass (View): @method_decorator (wrapper)defGet (self,request):returnRender (Request,'add_class.html') defPost (self,request): Class_name= Request. Post.get ('class_name') models. Classes.objects.create (Name=class_name)returnredirect'/class_list/')
Common values associated with request object requests and response objects
Path_info return user access URL, not including domain name
The string representation of the HTTP method used in the methods request, all uppercase.
Get a Class Dictionary object that contains all the HTTP GET parameters
Post class Dictionary object with all HTTP POST parameters
Body request body, byte type requested. The data from the post is extracted from the body.
Property
Property: Django encapsulates the request line, header information, and content body in the request message into attributes in the HttpRequest class. Except for special instructions, the others are read-only. 0.httprequest.scheme A string that represents the request scheme (typically HTTP or HTTPS)1. Httprequest.body A string that represents the body of the request message. It is useful when dealing with non-HTTP forms of messages, such as binary images, Xml,json, and so on. However, if you are working with form data, it is recommended that you use Httprequest.post. In addition, we can also use the Python class file method to manipulate it, the details refer to Httprequest.read (). 2. Httprequest.path A string that represents the requested path component (without a domain name). For example:"/music/bands/the_beatles/"3. Httprequest.method A string that represents the HTTP method used by the request. You must use uppercase. For example:"GET"、"POST"4. Httprequest.encoding A string that represents the encoding of the submitted data (if None is a setting that uses Default_charset, the default is'Utf-8'). This property is writable and you can modify it to modify the encoding used to access the form data. Next, any access to the property, such as reading data from GET or POST, will use the new encoding value. If you know that the encoding of the form data is not default_charset, use it. 5. Httprequest.get A dictionary-like object that contains all the parameters of an HTTP GET. Please refer to the Querydict object for details. 6. Httprequest.post A dictionary-like object that is encapsulated as a Querydict object if the request contains form data. The POST request can have an empty post dictionary-if a form is sent via the HTTP POST method, but there is no data in the form, the Querydict object is still created. Therefore, you should not useifRequest. Post to check if the Post method is used;ifRequest.method = ="POST"also: If you upload a file using POST, the file information will be included in the Files property. 7. HttpRequest.Cookies A standard Python dictionary that contains all the cookies. Both the key and the value are strings. 8. Httprequest.files A dictionary-like object that contains all the uploaded file information. Each key in the FILES is<input type="file"Name=""/>in the name, the value is the corresponding data. Note that FILES are submitted only if the requested method is post and the<form> with Enctype="Multipart/form-data"data is included in the case. Otherwise, FILES will be an empty dictionary-like object. 9. Httprequest.meta A standard Python dictionary that contains all HTTP headers. The specific header information depends on the client and server, and here are some examples: the length of the body of the content_length--request (is a string). The MIME type of the body of the content_type--request. http_accept--response to content that can be received-Type. The http_accept_encoding--response can receive the encoding. The http_accept_language--responds to the languages that can be received. http_host--the HTTP HOST header sent by the customer service side. Http_referer--referring page. The USER of the http_user_agent--client-The agent string. query_string--the query string as a single string (in unresolved form). The IP address of the remote_addr--client. The host name of the remote_host--client. remote_user--the user after server authentication. request_method--A string, for example"GET"Or"POST". The host name of the server_name--server. The port of the server_port--server (is a string). As you can see from above, any HTTP header in the request is converted to a META key except Content_length and CONTENT_TYPE, all uppercase letters are capitalized and the connector is replaced with an underscore, followed by a HTTP_ prefix. So, a called X-Bender's head will be converted to the Http_x_bender key in META. 10. Httprequest.user an object of type Auth_user_model that represents the currently logged-on user. If the user is not currently logged in, the username is set to an instance of Django.contrib.auth.models.AnonymousUser. You can differentiate them by is_authenticated (). For example:ifrequest.user.is_authenticated ():#Do something for logged-in users. Else: #Do something for anonymous users.user is only available when Django enables Authenticationmiddleware middleware. -------------------------------------------------------------------------------------Anonymous Userclassmodels. The Anonymoususer Django.contrib.auth.models.AnonymousUser class implements the Django.contrib.auth.models.User interface, but has the following distinct points: ID is always non E. Username is always an empty string. Get_username () returns an empty string forever. Is_staff and Is_superuser are always false. Is_active is always False. Groups and user_permissions are always empty. Is_anonymous () returns true instead of false. Is_authenticated () returns false instead of true. Set_password (), Check_password (), Save (), and delete () raise Notimplementederror. NewinchDjango 1.8: Added Anonymoususer.get_username () to better simulate django.contrib.auth.models.User. 11. Httprequest.session A dictionary-like object that is readable and writable, representing the current session. Available only if Django enables session support. See the documentation for the session for complete details. Request Property Correlation
View CodeMethod
1. Httprequest.get_host () returns the original host of the request from Http_x_forwarded_host (if Use_x_forwarded_host is turned on, default is False), and Http_host header information is returned. If the two headers do not provide a corresponding value, use server_name and server_port in THE PEP3333are described in detail. Use_x_forwarded_host: A Boolean value that specifies whether to use X first-forwarded-The Host header can be used only if the proxy has the header set. For example:"127.0.0.1:8000"Note: The Get_host () method will fail when the host is behind multiple agents. Unless you use middleware to rewrite the header of the agent. 2. Httprequest.get_full_path () returns path if the query string can be added. For example:"/music/bands/the_beatles/?print=true"3.httprequest.get_signed_cookie (Key, Default=raise_error, salt="', max_age=None) returns the value corresponding to the signed cookie and returns django.core.signing.BadSignature if the signature is no longer valid. If the default parameter is supplied, no exception is thrown and the value of default is returned. The optional parameter salt can be used to provide additional protection against security key brute force attacks. The Max_age parameter is used to check the timestamp of the cookie to ensure that the cookie does not take longer than max_age seconds. Copy Code>>> Request.get_signed_cookie ('name') 'Tony'>>> Request.get_signed_cookie ('name', salt='Name-salt') 'Tony' #Suppose you use the same salt when setting up a cookie>>> Request.get_signed_cookie ('Non-existing-cookie') ... Keyerror:'Non-existing-cookie' #An exception is triggered when there is no corresponding key>>> Request.get_signed_cookie ('Non-existing-cookie', False) False>>> Request.get_signed_cookie ('Cookie-that-was-tampered-with') ... Badsignature: ...>>> Request.get_signed_cookie ('name', max_age=60) ... Signatureexpired:signature Age1677.3839159 > 60seconds>>> Request.get_signed_cookie ('name', False, max_age=60) False to copy code4. Httprequest.is_secure () returns True if the request is secure, that is, the request was initiated over HTTPS. 5. Httprequest.is_ajax () returns True if the request was initiated through XMLHttpRequest, by checking that the corresponding header of the Http_x_requested_with is a string'XMLHttpRequest'. Most modern JavaScript libraries will send this header. If you write your own XMLHttpRequest call (on the browser side), you must manually set this value to allow Is_ajax () to work. If a response needs to be initiated by Ajax based on the request, and you are using some form of caching such as the Django cache middleware, you should use Vary_on_headers ('Http_x_requested_with'decorate your view to allow the response to be cached correctly. Request related Methods
View CodeResponse object Use
Passing strings
from Import = HttpResponse ('here's The text of the Web page.' ) )response = HttpResponse ('Text only, please. ', content_type='text/plain')
Set or delete response header information
Response = HttpResponse () response['content-type'text/html; CharSet = UTF-8'del response['content-type']
Property
Httpresponse.content: Response Content
Httpresponse.charset: Encoding of response content
Httpresponse.status_code: Status code of the response
Jsonresponse Object
Jsonresponse is a subclass of HttpResponse that is specifically used to generate JSON-encoded responses.
From django.http import Jsonresponse
Response = Jsonresponse ({' foo ': ' Bar '})
Print (response.content)
B ' {"foo": "Bar"} '
The default is to pass only the dictionary type, and if you want to pass a non-dictionary type, set the Safe keyword parameter.
Response = Jsonresponse ([1, 2, 3], Safe=false)
Django Shortcut Functionsrender ()
Django View (view)