A detailed description of how Django passes temporary data

Source: Internet
Author: User
Summarize the recent temporary data transfer.

There are three ways to http://www.php.cn/wiki/422.html "target=" _blank ">cookie,session,cache

First of all, what would be the choice for me, the cookie will be understood on the line, I am not used, because the user will close the cookie, and need to pass with HttpResponse, there are limitations

The session is also, in the configuration is not selected according to the cookie, according to the system default database is good

The cache is put into memory, easy to use and simple, that is, the memory ... can also be put in the library, according to the actual situation to consider it

Here are the three ways to configure and use the

A: Cookies

    • Get cookies

HttpRequest.Cookies

Returns a standard dictionary

Contains all cookies, the key value is str

    • Storing cookies

Httpresponse.set_cookie (Key, value= ", Max_age=none, Expires=none, path= '/', Domain=none, Secure=none, Httponly=False )

Max_age the length of time to save in seconds, when none is in sync with the client

Domain to set a cross-domain cookie

Domain= ". Lawrence.com" will set a cookie that is readable by www.lawrence.com, blogs.lawrence.com, and calendars.lawrence.com. Otherwise, the Cookie will only be read by the domain where it is set.

Can be written domian=[], will not error, but there is no test whether it can really cross the station

Httponly=false block the client's JS read cookie when set to True

    • Delete operation

Delete_cookie (Key, path= '/', Domain=none)

Deletes the cookie specified by key and does not occur when the cookie does not exist

Should be consistent when Set_cookie specifies that path is deleted with domain, otherwise it will not be deleted

    • Other content

Because it is a standard dictionary, request. cookies[' key ']= ' value ' can also put content in a cookie, but the value is lost when passed to the next view.

The cookie set in a view needs to be passed to the next view to be used, such as:

View1:res = Httpresponseredirect (revers ("Namespace:name") Res.set_cookie (' Key_set ', ' Value_set_view1 ', 60) # There's no way to get The cookie print (request) is not present. Cookies) # Direct settings Cookies cookies[' key_dict ' = ' values_dict ' # Here you can see the contents of the above settings print (request. COOKIES) Return res view2: Suppose the above response is the print (request) pointing to this. COOKIES) # Here you can see the Key_set set by the set above, but the key_dict set by the dictionary is not

Two: Using session

Adding Django.contrib.sessions.middleware.SessionMiddleware in the middleware plug-in set

django1.10 to middleware,1.08 for middleware_classes

And there should be ' django.contrib.sessions ' in Installed_apps.

You can set the session to be cookie-based, file, memory, database

    • Add ' django.contrib.sessions ' to Installed_apps based on the database

After the configuration is complete, run manage.py migrate

    • Session_engine based on the file setting is "Django.contrib.sessions.backends.file".

At the same time can set Session_file_path, to specify the location of the file, otherwise use the system default value, not modified is/tmp

    • Cookie-based sessions are not recommended because customers can set up non-use cookies

Set Session_engine to "Django.contrib.sessions.backends.signed_cookies"

    • Based on the cache, when the cache is set and the cache location is set to memory, the session can be set to cache-based, which is recommended only if the cache uses memcached as the back end.

Otherwise, it would be better to use the cache directly, with more flexibility and less load

The session_engine is set directly at the outermost layer of the setting.py

setting.py

Session_engine = "Django.contrib.sessions.backends.file"

    • Using sessions

Base class for Session

Backends.base.SessionBase

Get session in view

Request.session get a standard class dictionary

Method is the same as the dictionary (no private method is used)

session[' fav_color ' = ' Blue ' Set session

Get (key, Default=none)

For example: Fav_color = Request.session.get (' Fav_color ', ' Red ')

Pop (key) deletes the key-value pair and returns the value

Example: Fav_color = Request.session.pop (' Fav_color ')

Keys ()

Items ()

SetDefault (Key[,default=none]) returns the corresponding value when key is present, adds a key-value pair to the dictionary when it does not exist, and returns the default value

Clear ()

Special methods

Flush ()

Deletes the current session data and deletes the session's cookie. This action can be used when the user logs off

Set_expiry (value) sets the session timeout length

Value can be set to a positive integer, Datatime/timedelta,0,none

Integer (seconds) n seconds no action expires

Datatime/timedelta the time point expires

0 Close Browser expires

None is the same as the global default value

Get_expiry_age () Distance session expires when the session has expired or has not customized expiration information, none is returned

Keyword parameters

Odification: The last modification time of a session, the default is that you can now pass a previous or subsequent value to determine how long it will expire

Expory Custom Expiration Information

Get_expiry_date () returns the expiration date, expired, or not customized save time of the returned cookie

Get_expire_at_browser_close ()

Returns TRUE or false, depending on whether the user's session cookie expires when the user's browser is closed.

The clear_expired () class method clears the expired session from the storage of the session.

Cycle_key () creates a new session while preserving the current session data.

Three: Using caching

    • Setting up the cache (use the built-in background when memory is sufficient and necessary to configure memcached)

Cache in File

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.filebased.FileBasedCache ',

' Location ': '/var/tmp/django_cache ', # File path, when under win change to ' C:/tmp/django_cache '

}

}

The path is an absolute path and is a directory that requires 42 (read and write) permissions for the current user

Cached in the database

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.db.DatabaseCache ',

' Location ': ' my_cache_table ', #表名, legal and unused

}

}

Python manage.py createcachetable create cache table with table name specified by location

Cached in memory (by default)

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.locmem.LocMemCache ',

' Location ': ' Unique-snowflake ', # Memory only needs to be configured when there are multiple, only one memory is not configured

}

}

Virtual cache: does not cache, but reserved interfaces are used to ensure consistency in the development production environment

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.dummy.DummyCache ',

}

}

    • Setting the caches parameter

Timeout time-Out default 300 is five minutes

Version default cache build number

OPTIONS: This parameter should be uploaded to the cache backend. A valid list of options is different depending on the backend of the cache, and the cache supported by the third-party library will configure these options directly to the underlying cache library.

Caching the backend implementation of its own selection policy (file, database, memory) will fulfill these options:

Max_entries: The maximum number of entries allowed for the cache, and the old value will be deleted if this number is exceeded. This parameter is 300 by default.

Cull_frequency: The percentage of entries that are deleted when the max_entries is reached. The actual ratio is 1/cull_frequency, so setting Cull_frequency to 2 deletes half of the cache when the value set by Max_entries is reached. This parameter should be an integer, and the default is 3.

Setting the value of Cull_frequency to 0 means that when max_entries is reached, the cache is emptied. Some cache backend (database in particular) will be at the expense of many cache misses.

Instance:

Cache in memory, and timeout is 60*10 600 seconds, cache 500, delete 1/5 each time

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.locmem.LocMemCache ',

' TIMEOUT ': 600,

' OPTIONS ': {

' Max_entries ': 500,

' Cull_frequency ': 5

}

}

}

    • Cache policy: Cache entire station, cache view, cache template Fragment

    • Cache Entire Station:

setting.py

1.08

Middleware_classes = (

' Django.middleware.cache.UpdateCacheMiddleware ',

' Django.middleware.common.CommonMiddleware ',

' Django.middleware.cache.FetchFromCacheMiddleware ',

)

1.10

Middleware = [

' Django.middleware.cache.UpdateCacheMiddleware ',

' Django.middleware.common.CommonMiddleware ',

' Django.middleware.cache.FetchFromCacheMiddleware ',

]

Don't be wrong about the order.

Then add the value at the outermost of the setting.py

cache_middleware_alias– the alias of the cache used for storage, not set to ' default '

cache_middleware_seconds– How many seconds each page needs to be cached.

cache_middleware_key_prefix– if the cache is shared by multiple Web sites using the same Django installation, set the value to the current site name, or another unique string representing the Django instance, to avoid KEY collisions. If you don't care, you can set an empty string.

Single View Cache

From Django.views.decorators.cache import Cache_page

@cache_page (60 * 15)

def my_view (Request):

Pass

Multiple URLs point to the same view, and each URL is cached separately, such as:

URL (r ' ^foo/([0-9]{1,2})/$ ', My_view),

Foo/12

FOO/13 uses a different cache, but two 12 uses the same

@cache_page (cache= "Special_cache")

For example, the specified cache will be used only

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.locmem.LocMemCache ',

' TIMEOUT ': 600,

' OPTIONS ': {

' Max_entries ': 500,

' Cull_frequency ': 5

}

},

' Special_cache ': {

' Backend ': ' Django.core.cache.backends.locmem.LocMemCache ',

' TIMEOUT ': 600,

' OPTIONS ': {

' Max_entries ': 500,

' Cull_frequency ': 5

}

}

}

Specify how to cache in a URL

When you need to access/cache/and/nocache/, it also points to a page, but one cache does not cache

You can specify which page cache is on the URL, not on the view

URL (r ' ^cache/$ ', Cache_page (my_view), name= ' cache '),

URL (r ' ^nocache/$ ', My_view, name= ' NoCache '),

Template caching

{% Load cache%}

{% cache duration (seconds) name%}

{% Endcache name%}

More flexible use of caching

Import Django.core.cache's caches in views

CAD = caches[' Default ' # The name here is the same as the configuration in caches

cas = caches[' Special_cache ']

Common methods

Cad.set (' key ', ' value ', time-duration) default or custom value

Cad.get (' key ') key does not exist return none, you can also specify a default of Get (' key ', ' default value '), no key to return ' default value '

Cad.add (' key ', ' value ') increases key-value when key does not exist, does not operate when key already exists, value is previous

Set_many ({' Key1 ': ' v1 ', ' K2 ': ' V2 '})

Get_many ([' Key1 ', ' key2 ' ...]) gets the value of the key in the list return value to the standard dictionary

Delete (' key ')

Delete_many ([' Key1 ', ' Key2 ']) when key does not exist

Clear () Delete all caches

Close () closes the cache

CAD.INCR (' key ', value) equals cad[' key ']+=value of course, just equivalent, can't do that

Because the underlying is using New_value = value + Delta

, then. When value is ' a ', it is also possible, as long as the + can be used

CAD.DECR (' key ', value) minus, ibid.

Cached versions: version can pass in the same key, but save a different value, using version to implement

Cad.set (' Key1 ', ' Valu ', version=3) set Key1 to Version3,

Ca.set (' AA ', ' DD ', version=3)

Ca.set (' AA ', ' e ', version=4)

Print (Ca.get (' AA ', version=3)) #=> DD

Print (Ca.get (' AA ', version=4)) #=> E

Incr_version (' key ', value) the same, value supports +-can

Decr_version (' key ', value)

However, it is not recommended to use STR directly, and it is not recommended to use your own class.

But when you do need to use a custom class to populate version, the method you need to override is (python3.x)

Str

Add

Sub

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.