How django transmits temporary data

Source: Internet
Author: User
Tags timedelta
This article explains how django transmits temporary data and summarizes the recently used temporary data transfer methods.

There are three methods: # wiki/422.html "target =" _ blank "> cookie, session, cache

First, let me explain how to select the cookie. the cookie will be understood. I am not very familiar with it because the user will disable the cookie and the cookie needs to be passed with HttpResponse, which has limitations.

The session is the same. during configuration, the cookie is not selected and the default database is used.

The cache is put into the memory, which is convenient and easy to use, that is, the memory occupied... can also be put in the library. consider it based on the actual situation.

The following is how to configure and use these three methods:

I. cookie

  • Get cookie

HttpRequest. COOKIES

Returns a standard dictionary.

Contains all cookies. The key value is str.

  • Store cookies

HttpResponse. set_cookie (key, value = '', max_age = None, expires = None, path = '/', domain = None, secure = None, httponly = False)

Max_age sets the storage duration in seconds. if it is set to None, the duration is synchronized with the client.

Domain sets a cross-domain cookie

Domain = ".lawrence.com" sets a Cookie that can be read by www.lawrence.com, blogs.lawrence.com, and calendars.lawrence.com. Otherwise, the Cookie can only be set to read its domain.

It can be written as domian = []. no error is reported, but it is not tested whether cross-site communication is possible.

Httponly = False when set to True, the client's js is blocked from reading cookies.

  • Delete operation

Delete_cookie (key, path = '/', domain = None)

Deletes the cookie specified by the key. if the cookie does not exist, nothing will happen.

When set_cookie specifies the path and domain, it should be consistent when deleted; otherwise, it will not be deleted.

  • Other content

Request. COOKIES ['key'] = 'value' can also store the content in COOKIES, but the value is lost when it is passed to the next view.

The cookie set in a view must be passed to the next view for use. for example:

View1: res = HttpResponseRedirect (revers ("namespace: name") res. set_cookie ('key _ set', 'value _ set_view1 ', 60) # The current cookie print (request. COOKIES) # directly set COOKIES ['key _ dict '] = 'values _ dict' # Here we can see the content print (request. COOKIES) return res view2: suppose the above Response is the print (request. COOKIES) # Here we can see the key_set set above, but the key_dict set through the dictionary does not exist.

II. use session

Add django. contrib. sessions. middleware. SessionMiddleware in the middleware plug-in set

Django1.10 is MIDDLEWARE and 1.08 is MIDDLEWARE_CLASSES.

In addition, INSTALLED_APPS should contain 'Django. contrib. session '.

You can set the session to cookie-based, File, memory, and database.

  • Add 'Django. contrib. session' to INSTALLED_APPS based on the database.

After the configuration is complete, run manage. py migrate

  • Set SESSION_ENGINE to "django. contrib. sessions. backends. file" based on the file ".

You can also set SESSION_FILE_PATH to specify the file storage location. Otherwise, the default value is/tmp.

  • Cookie-based sessions are not recommended because customers can set the cookie-based session

Set SESSION_ENGINE to "django. contrib. sessions. backends. signed_cookies"

  • Based on cache, sessions can be set to cache-based when the cache is set and the cache storage location is set to memory. this is recommended only when Memcached is used as the backend.

Otherwise, it is better to use the cache directly, with higher flexibility and lower load.

SESSION_ENGINE is directly set to the outermost layer of setting. py.

Setting. py

SESSION_ENGINE = "django. contrib. sessions. backends. file"

  • Use session

Session base class

Backends. base. SessionBase

Get session in view

Request. session get a standard class dictionary

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

Session ['fav _ color'] = 'blue' sets the session

Get (key, default = None)

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]): If the key exists, the corresponding value is returned. if the key does not exist, the key-value pair is added to the dictionary and the default value is returned.

Clear ()

Special method

Flush ()

Delete the current session data and delete the Cookie of the session. This operation can be used when a user logs out.

Set_expiry (value) sets the session timeout length

Value can be set to a positive integer, datatime/timedelta, 0, None

Integer (second) n seconds. expired if no operation is performed

Datatime/timedelta expired at this time point

0. when the browser is closed, it expires.

None is the same as the global default.

Get_expiry_age () is from the session expiration time. when the session has expired or custom expiration information is not displayed, None is returned.

Keyword parameter

Odification: The last modification time of the session. by default, a previous or later value can be passed to determine how long the session will expire.

Expory custom expiration information

Get_expiry_date () returns the expiration date, which has expired or has not been customized.

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 expired sessions from the session storage.

Cycle_key () creates a new session and retains the current session data.

III. use cache

  • Set cache (use the built-in background to configure Memcached when the memory is sufficient and necessary)

Cached in a file

CACHES = {

'Default ':{

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

'Location': '/var/tmp/django_cache', # file path. change it to 'C:/tmp/django_cache 'under win'

}

}

The path is an absolute path. it is a directory and requires 42 (read/write) permissions of the current user.

Cache in database

CACHES = {

'Default ':{

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

'Location': 'My _ cache_table ', # The table name, which is legal and has not been used.

}

}

Python manage. py createcachetable: create a cache table. The table name is specified by LOCATION.

Cache in memory (default)

CACHES = {

'Default ':{

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

'Location': 'unique-snowflake ', # The memory needs to be configured only when there are multiple memories. if there is only one memory, no configuration is required.

}

}

Virtual Cache: no cache, but reserved interfaces are used to ensure consistency in the development and production environments.

CACHES = {

'Default ':{

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

}

}

  • Set CACHES parameters

TIMEOUT: the default TIMEOUT value is 300, that is, five minutes.

Default VERSION cache VERSION number

OPTIONS: this parameter should be passed to the cache backend. The valid option list varies depending on the cache backend. the cache supported by a third-party library directly configures these options to the underlying cache Library.

The cache backend implements its own selection policy (File, database, memory) to fulfill the following options:

MAX_ENTRIES: maximum number of entries allowed by the cache. if this number is exceeded, the old value will be deleted. the default value of this parameter is 300.

CULL_FREQUENCY: the ratio of entries to be deleted when MAX_ENTRIES is reached. The actual ratio is 1/CULL_FREQUENCY. Therefore, if the value of CULL_FREQUENCY is set to 2, half of the cache will be deleted when the value reaches the value set by MAX_ENTRIES. This parameter should be an integer. the default value is 3.

Setting the value of CULL_FREQUENCY to 0 means that when MAX_ENTRIES is reached, the cache will be cleared. Some cache backend (databases in particular) will be at the cost of a lot of cache loss.

Instance:

The cache is in the memory, and the timeout duration is 60*10 600 seconds. the number of cached records is 500, and each time 1/5 records are deleted.

CACHES = {

'Default ':{

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

'Timeout': 600,

'Options ':{

'Max _ entries': 500,

'Pull _ FREQUENCY ': 5

}

}

}

  • Cache policy: cache the entire site, cache view, cache template fragment

  • Cache whole site:

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 ',

]

Make sure that the order is correct.

Then add the value to the outermost layer of setting. py.

CACHE_MIDDLEWARE_ALIAS-the alias used for storing the cache. If this parameter is not set, it is 'default'

CACHE_MIDDLEWARE_SECONDS-the number of seconds each page needs to be cached.

CACHE_MIDDLEWARE_KEY_PREFIX-if the cache is shared by multiple websites installed with the same Django, set this value to the current website name or a unique string that can represent the Django instance, to avoid key conflicts. If you don't care about it, you can set it to a null string.

Single view Cache

From django. views. decorators. cache import cache_page

@ Cache_page (60*15)

Def my_view (request ):

Pass

Multiple URLs direct to the same view, and each URL is cached separately, for example:

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

Foo/12

Foo/13 uses different caches, but two 12 uses the same

@ Cache_page (60*15, cache = "special_cache ")

For example, only the specified cache is used.

CACHES = {

'Default ':{

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

'Timeout': 600,

'Options ':{

'Max _ entries': 500,

'Pull _ FREQUENCY ': 5

}

},

'Special _ cache ':{

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

'Timeout': 600,

'Options ':{

'Max _ entries': 500,

'Pull _ FREQUENCY ': 5

}

}

}

Specify how to cache in the url

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

You can specify the page cache on the url instead of the view.

Url (r' ^ cache/$ ', cache_page (60*15) (my_view), name = 'cache '),

Url (r' ^ nocache/$ ', my_view, name = 'nocache '),

Template cache

{% Load cache %}

{% Cache duration (SEC) name %}

{% Endcache name %}

More flexible use of cache

Import the caches of django. core. cache 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', duration). If no duration is set, the default value or custom value is used.

If the cad. get ('key') key does not exist, None is returned. you can also specify the default value get ('key', 'default '). If no key exists, 'default' is returned'

Cad. add ('key', 'value') adds a key-value when the key does not exist. if the key already exists, no operation is performed. The value is still the previous value.

Set_1_( {'key1': 'v1 ', 'K2': 'V2 '})

Get_keys (['key1', 'key2'...]) obtain the value of the key in the list. the returned value is a standard dictionary.

Delete ('key ')

Delete_keys (['key1', 'key2']) when the key does not exist

Clear () deletes all caches

Close () close cache

Cad. incr ('key', value) is equivalent to cad ['key'] + = value. of course, it is equivalent to, but cannot.

The underlying layer uses new_value = value + delta

, So when the value is 'A', it is also possible, as long as it can be used +

Cad. decr ('key', value) minus, same as above

Cache VERSION: the version can be used to input the same key, but save different values.

Cad. set ('key1', 'valu', version = 3) set key1 to version3,

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

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

Print (ca. get ('A', version = 3) # => dd

Print (ca. get ('A', version = 4) # => e

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

Decr_version ('key', value)

However, you are not recommended to use str directly, or use your own classes.

But when you do need to use a custom class to fill the version, the methods to be overwritten are (python3.x)

Str

Add

Sub

The above is a detailed description of how django transmits temporary data. For more information, see other related articles in the first PHP community!

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.