Python Learning note-day18-django (Part One)

Source: Internet
Author: User

Routing system

The first general Setup method

From Django.conf.urls import include, Urlfrom django.contrib import adminfrom indexpage import viewsurlpatterns = [url (R ' ^$ ', views.indexpage), url (r ' ^reg/$ ', views.reg), url (r ' ^home/$ ', views.home),]


Second dynamic URL

URL (r ' ^dynamic/(\d+)/$ ', views.dynamic), #向dynamic参数传参数, by default it is transmitted sequentially
URL (r ' ^dynamic/(? p<v1>\d+)/(? p<v2>\d+) $ ', views.dynamic), # v1 v2 is the parameter of the function called


Third grading match

URL (r ' ^app01/', include ("App01.urls")), #app01为django下的application, requires APP01 under also configure url.py access address as: http://IP/app01/dynamic


###################################################


Middleware

Django processing is a request, the first need to pass through the middleware, and then in the URL to invoke the first close views.

In the middleware here we can filter and process the request,

Installation method:

The middle.py in the middleware directory under project is our middleware.

Make the following settings in the setting.py of the project

middleware_classes = (' Django.contrib.sessions.middleware.SessionMiddleware ', ' Django.middleware.common.CommonMiddleware ', ' django.middleware.csrf.CsrfViewMiddleware ', ' Django.contrib.auth.middleware.AuthenticationMiddleware ', ' Django.contrib.auth.middleware.SessionAuthenticationMiddleware ', ' Django.contrib.messages.middleware.MessageMiddleware ', ' Django.middleware.clickjacking.XFrameOptionsMiddleware ' , ' Django.middleware.security.SecurityMiddleware ', ' middleware.middle.xxx ', #这里就是我们的中间件, with its own middleware)




Operating mechanism:

The schematic is as follows:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7D/67/wKioL1bnwjeRR8jQAABoZyVDBhk438.png "title=" Middleware01.png "alt=" Wkiol1bnwjerr8jqaabozyvdbhk438.png "/>

Data trends:


Blue: The normal process


Red: The direction of the data when Mid01 's process_request handles the request if it encounters a return statement


Purple: The trend of data when views encounter anomalies


Each middleware has a default number of functions that need to be implemented at the time of customization:

Django adds all of the middleware's same name functions into a list (there are several functions by default, there are several lists)

When the request enters, Django invokes the function in the list in turn to process the request.

Specific functions can refer to the official documentation


##############################################################


The Cookie/session in Django


In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side.

Cookie Rules

1, cookies are stored in a dictionary, access is as long as the key to access the session can get the corresponding value

2. Store to Client

Advantages:

Data exists on the client side, alleviating the pressure on the server and improving the performance of the website.

Disadvantages:

1, security is not high: in the client machine can easily be viewed or cracked user reply information


1, the session is stored in a dictionary, access as long as the key to access the session can be the corresponding value


2. The key value that starts with the underscore in the session dictionary is the Django internal reserved key value. The framework will only use session variables that start with a few underscores, and unless you know their specific meaning and are willing to keep up with Django changes, it's best not to use the variables that start with these underscores, which will let Django mess with your app.

3, do not use a new object to replace the request.session, do not access its properties,

4, session stored on the server side,

Advantages: Data storage is relatively safe and data exchange is convenient.

Disadvantage: If you store more data, large amount of traffic, the comparison consumes server-side resources, resulting in a decrease in overall site performance.

How to use

request.session[' Is_login '] #设置

Request.session.get (' Is_login ', False) #获取

Del request.session[' Is_login '] #删除



#############################################################################


The form in Django

The form in Django has two functions

1. Validation of user submitted data

2. Generate HTML tags.


Use an example to illustrate the problem


Create a new project: MyWeb

django-admin.py Startproject MyWeb


Go to the MyWeb folder and create a new APP:APP01

Python manage.py Startapp App01


Create a new forms.py file in the App01 folder

From Django Import Forms Class MyForm (forms. Form): username = forms. Integerfield () Password = forms. Integerfield ()


Our view function is in views.py

# coding:utf-8from django.shortcuts import renderfrom django.http import  httpresponse #  introduces the form class From .forms import myform def index (Request) We created:     if request.method ==  ' POST ':     #  Get the request method for post   submit form request         form = myform (ask. POST)    #  form  include submitted data         if  Form.is_valid ():         #  If the submitted data is legal              a = form.cleaned_data[' A ']             b = form.cleaned_data[' B ']             return httpresponse (str (a)  + int (b))      else:#  when normalVisit         form = myform ()     return  render (request,  ' index.html ',  {' form ':  form})

The corresponding template file index.html (the following code is written in the body)

<form method= ' post ' >{{form}}<input type= "Submit" value= "Submit" ></form>


and write this function in the urls.py.

Urlpatterns = Patterns ("", url (r ' ^$ ', ' app01.views.index ', name= ' home '), # This behavior adds URL route url (r ' ^admin/', include (ADM In.site.urls)),)



###################################################################


By default, AJAX requests use the Get method. If you want to use the Post method, you can set the type parameter value. This option also affects how content in the data option is sent to the server.



The $.ajax () function relies on the information provided by the server to process the returned data. If the server reports that the returned data is XML, then the returned result can be traversed using either a normal XML method or a jquery selector. If other types, such as HTML, are seen, the data is treated in textual form.


The datatype option also allows you to specify different methods of data processing. In addition to simple XML, you can specify HTML, JSON, JSONP, script, or text.


Where the data returned by the text and XML types is not processed. The data simply passes the XMLHttpRequest responsetext or Responsehtml property to the success callback function,


' Note ', we must make sure that the MIME type reported by the Web server matches the datatype we have chosen. For example, XML, the server side must declare Text/xml or Application/xml to obtain consistent results.


If specified as an HTML type, any inline JavaScript will be executed before the HTML is returned as a string. Similarly, if the script type is specified, the server-side generation of JavaScript is executed before it is returned as a textual data.


If the JSON type is specified, the obtained data is parsed as a JavaScript object, and the constructed object is returned as a result. To achieve this, he first tried to use Json.parse (). If the browser is not supported, a function is used to build it. JSON data is a structured data that can be easily parsed by JavaScript. If the obtained data file resides on the remote server (the domain name is different, that is, the data is obtained across domains), you need to use the JSONP type. With this type, a query string parameter callback= is created? , this parameter is appended to the URL of the request. The server side should precede the JSON data with a callback function name in order to complete a valid JSONP request. If you want to specify the parameter name of the callback function instead of the default callback, you can set the JSONP parameter of the $.ajax ().



If you are working with $.ajax () data, you need to use a callback function. Beforesend, error, Datafilter, success, complete.


Beforesend is called before the request is sent, and a xmlhttprequest is passed in as a parameter.

Error is called when the request is faulted. Incoming XMLHttpRequest object, a string describing the type of error, and an exception object (if any)

Datafilter is called after the request succeeds. The returned data is passed in as well as the value of the "DataType" parameter. and the new data (possibly processed) must be returned to the success callback function.

Success called after the request. The data after the incoming return, and the string containing the success code.

Complete the function is called after the request is completed, regardless of success or failure. The incoming XMLHttpRequest object, and a string containing the success or error code.



Describe:

Save the data to the server and display the information when it succeeds.

JQuery Code:

$.ajax ({type: "POST", url: "some.php", Data: "Name=john&location=boston", Success:function (msg) {alert (   "Data Saved:" + msg); }});


Function adduser (ARG) {    //console.log ($ (ARG). Find ("#saveUsername"). EQ (0). Val ());     //console.log ($ (ARG). Find ("#firstPwd"). EQ (0). Val ());     // Console.log ($ (ARG). Find ("#saveGender"). EQ (0). Val ());     $.ajax ({         type: "POST",         url: "/add/",         data:{              "username": $ (ARG). Find ("#saveUsername"). EQ (0). Val (),              "Password": $ (ARG). Find ("#firstPwd"). EQ (0). Val (),              "Gender": $ (ARG). Find ("#saveGender"). EQ (0). Val (),         },        success:function (data) {             if (data== "err") {                 console.log (data);                 console.log ("123")                  $ (ARG). Find ("#saveUsername"). EQ (0). CSS ("Border-color", "Red")              }else {                 console.log (data);                 $ (ARG). Modal (' Toggle ');                 window.location.reload ();             }         }    });} 


#######################################################################

Cache


Django is a dynamic web site, generally need to generate real-time access to the Web page, display to the visitor, so that the content can be changed at any time, but from the database read many times the need to take the data out, more than from memory or hard disk to read out the cost of much more.


For a given URL, try to find the URL from the cache, if the page in the cache, directly back to the cached page, if not in the cache, a series of operations (such as database), save the generated page content to the cache system for the next use, and then return the generated page content.


Once the cache is set up, the simplest app is to cache your entire site.


You need to add two middleware to Middlewrae_ CLASSES:django.middleware.UpdateCacheMiddleware and Django.middleware.cache.FetchFromCacheMiddleware, note that the Updatecache middleware must be placed in First, the FETCH middleware must be final (because the order of the middleware determines the order in which it runs) see the following example:


Middleware_classes = (

' Django.middleware.cache.UpdateCacheMiddleware ',

' Django.middleware.common.CommonMiddleware ',

' Django.middleware.cache.FetchFromCacheMiddleware ',

)

Then you need to include the following required settings in the project configuration file:


Cache_middleware_alias: The cache alias used to store

Cache_middleware_seconds: The number of seconds each page should be cached

Cache_middleware_key_prefix: The key prefix, when multiple sites use the same configuration, this can be set to avoid conflicts; If you don't care, you can use an empty string to advise you not to do this.

If the request or the head of the response is allowed, the cache middleware caches the 200 get or head corresponding pages. The same URL but different query parameters will be considered different accordingly and thus be cached separately.


If you set the Cache_middleware_anonymous_only to True, then only anonymous requests are cached, which is the simplest way to disable caching of non-anonymous user pages, and be sure that the authentication middleware is enabled.


The cache middleware expects a head request to be responded to by a response to a GET request with the same response header, because the cache middleware can return to a head request directly with a get response.


In addition, the cache middleware automatically sets a small amount of header information to each httpresponse:


When a fresh page is requested, a last_modified head is played with the current time.

will be set to expires head with the current time plus cache_middleware_seconds value

Use the value of Cache_middleware_seconds to set the maximum age of a page for the Cache-control (provided the view function is not set)


Caching of each view function


A more granular approach to using the caching framework is to cache the output of a single view function. Django.views.decorators.cache defines a cache_page adorner, and the output of the view using the adorner is automatically cached.


Cache_page (timeout, [cache=cache name], [key_prefix=key prefix])


Cache_page accepts only one parameter and two keyword arguments,


Timeout is the cache time, in seconds

Cache: Specify which cached backend in your caches settings to use

Key_prefix: Specifies the cache prefix that can overwrite the value Cache_middleware_key_prefix in the configuration file

@cache_page (key_prefix= "site1")

def my_view (Request):

Using the cache adorner in a URL configuration file


Similar to the above, the position of the adorner has changed.


From Django.views.decorators.cache import Cache_page


Urlpatterns = (' ',

(R ' ^foo/(\d{1,2})/$ ', Cache_page (My_view)),

)




Reference Link: Http://www.cnblogs.com/wupeiqi


This article is from the "'ll Notes" blog, so be sure to keep this source http://timesnotes.blog.51cto.com/1079212/1751379

Python Learning note-day18-django (Part One)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.