Home > Backend Development > Python Tutorial > Detailed explanation of how Django transfers temporary data

Detailed explanation of how Django transfers temporary data

高洛峰
Release: 2017-03-23 14:52:27
Original
1980 people have browsed it

Summarize the temporary data transfer recently used

There are three methods,cookie,session,cache

Let me first tell you how to choose for me. I only need to understand cookies. I don’t use them often because users Cookies will be turned off and need to be passed along with the HttpResponse. There are limitations.

The same applies to sessions. When configuring, do not choose to use cookies and just follow the system default database.

cache In the memory, it is convenient and simple to use. It only takes up memory.... It can also be placed in the library. Consider it according to the actual situation.

The following is the configuration and use of these three methods

一: cookie

  • Get cookie

HttpRequest.COOKIES

Return a standard dictionary

Contains all cookies, the key values ​​are str

  • ##Storage cookies

  • ##HttpResponse.
set

_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)max_age is set and saved in seconds. The duration, when it is None, the duration is synchronized with the client

domain Set a cross-domain cookie

domain=".lawrence.com" will set a www.lawrence.com, blogs A cookie that is readable by both .lawrence.com and

calendar

s.lawrence.com. Otherwise, the cookie will only be read by the domain where it is set. can be written as domian=[], No error will be reported, but there is no test whether it can really cross-site

httponly=False When set to True, prevent the client's

js

from reading cookies

    Delete operation
  • ##delete
_cookie(key, path='/', domain=None)

Delete the cookie specified by key. Nothing will happen when the cookie does not exist

When set_cookie specifies path and domain, they should be consistent when deleting, otherwise they will not be deleted

Other content
  • Because it is a standard dictionary, request.COOKIES['key']='value' can also put the content in the cookie, but when it is passed to the next view, the value will be Lost
The cookie set in one view needs to be passed to the next view before it can be used, such as:

view1:
  res = HttpResponseRedirect(revers("namespace:name")
  res.set_cookie('key_set', 'value_set_view1', 60)
  # 在这里是没办法获取不到现在的这个cookie
  print(request.COOKIES)
  # 直接设置COOKIES
  COOKIES['key_dict'] = 'values_dict'
  # 这里可以看到上面设置的内容
  print(request.COOKIES)
  return res
  view2: 假设上面的Response就是指向这里的
  print(request.COOKIES)
  # 这里可以看到上面通过set设置的 key_set ,但是通过字典设置的key_dict就没有了
Copy after login
2: Use session

Add # in the middleware plug-in set ##django

.contrib.sessions.middleware.SessionMiddleware

django1.10 is MIDDLEWARE, 1.08 is MIDDLEWARE_CLASSESand there should be 'django.contrib.sessions' in INSTALLED_APPS.

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

Based on the database, add 'django.contrib.sessions' to INSTALLED_APPS

  • After the configuration is completed, run manage.py migrate

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

  • At the same time, you can set SESSION_FILE_PATH to specify the file storage location. Otherwise, use the system default value. If not modified, it will be /tmp

Cookie-based Session, not recommended, because customers can set not to use cookies

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

Based on

Cache
    , when the cache is set up and the cache storage location is set to memory, the session can be set to be cache-based. This is recommended only when the cache uses
  • Memcached

    as the backend Otherwise, it is better to use the cache directly, which has higher flexibility and smaller load.

  • Session_ENGINE can be directly set in the outermost layer of setting.py

setting.py

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

Use Session

  • Session's Base class

  • backends.base.SessionBase

Get session in view

request.session Get a standard class dictionary

The method is also the same as the dictionary (Do not use private methods)

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

For example: fav_color = request.session.pop('fav_color')

keys()

items()

setdefault(key[,default=None]) Returns the corresponding value when the key exists, and sets the key-value pair when it does not exist Add to dictionary and return default value

clear

()

Special methods

flush()

Delete the current session data and delete the session's cookies. This operation can be used when the user logs out

set_expiry(value) Set the session timeout length

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

Integer (seconds) Expiration if no operation is performed for n seconds

datatime/timedelta Expires at this time point

0 Expires when the browser is closed

None Same as the global default value

get_expiry_age() The length of time until the session expires. Returns None when the session has expired or the expiration information is not customized

Keyword parameters

odification : The last modification time of the session, the default is the current value. You can pass a value before or after to determine how long it will expire.

expory Customized expiration information

get_expiry_date() Returns the expiration date, expired or uncustomized returns the storage time of the cookie

get_expire_at_browser_close()

Returns True or False, depending on the user's session cookie when the user's browser is closed Will it expire?

clear_expired() class method Clears expired sessions from session storage.

cycle_key() Creates a new session while retaining the current session data.

Three: Use cache

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

Cache in file

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',

'LOCATION': '/var/tmp/django_cache', # File path, when changed to 'c:/tmp/django_cache' under win

}

}

The path is an absolute path, a directory, which requires the current user’s 42 (read and write) permissions

Cached in the database

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.db.DatabaseCache',

'LOCATION': 'my_cache_table', #Table name, legal And it can be unused

}

}

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

'LOCATION': 'unique-snowflake', # The memory only needs to be configured when there are multiple memories. If there is only one memory, there is no need to configure it.

}

}

Virtual cache: Do not cache, but retain Interface Used to ensure the consistency of the development and production environment

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.dummy.DummyCache',

}

}

  • Set CACHES parameters

TIMEOUT The default timeout time is 300 which is five minutes

VERSION The default cache version number

OPTIONS: This parameter should be Passed to the cache backend. The list of valid options varies depending on the cache backend, and caches supported by third-party libraries will configure these options directly into the underlying cache library.

The cache backend implements its own selection strategy (file, database, memory) and will implement the following options:

MAX_ENTRIES: The maximum number of entries allowed in the cache. If it exceeds this number, it will be old. The value will be deleted. The default value of this parameter is 300.

CULL_FREQUENCY: When MAX_ENTRIES is reached, the ratio of entries to be deleted. The actual ratio is 1 / CULL_FREQUENCY, so setting CULL_FREQUENCY to 2 will delete half of the cache when the value set by MAX_ENTRIES is reached. This parameter should be an integer, defaulting to 3.

Setting the value of CULL_FREQUENCY to 0 means that the cache will be cleared when MAX_ENTRIES is reached. For some cache backends (especially databases) this will come at the cost of many cache misses.

Example:

is cached in memory, and the timeout is 60*10 600 seconds, 500 items are cached , delete 1/5 each time

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' ,

'Timeout': 600,

## 'Options': {

'Max_entries': 500,

## 'Cull_frequency': 5

} }

}

}

  • Caching strategy: Cache the entire site, cache the view, cache the template fragment

  • Cache the entire 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',

]

Pay attention to the order.

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

CACHE_MIDDLEWARE_ALIAS – the alias for the stored cache, if not set, it will be 'default '

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

CACHE_MIDDLEWARE_KEY_PREFIX – If the cache is shared by multiple websites using the same Django installation, then this value Set to the current website name, or other unique string that can represent this Django instance to avoid key conflicts. If you don't care, you can set it to an empty string.

Single view cache

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)

def my_view(request):

pass

If multiple URLs point to the same view, each URL will be cached separately, such as:

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

foo/12

foo/13 uses different caches, but both 12 use the same

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

For example: only the specified cache will be used

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 . #When you need to access /cache/ and /nocache/, they also point to the same page, but one is cached and the other is not cached.

You can specify which page to cache on the url, not on 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 (seconds) 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 in CACHES The configuration is the same

cas = caches['special_cache']

Commonly used methods

cad.set('key','value',duration) If no duration is set, it will be taken Default value or custom value

cad.get('key') If the key does not exist, it will return None. You can also specify the default value get('key','default value'). If there is no key, it will return 'default value'. '

cad.add('key','value') When the key does not exist, add key-value. When the key already exists, no operation is performed. The value is still the previous value

set_many ({'key1':'v1','k2':'v2'})

get_many(['key1','key2'..]) Get the value of the key in the list The return value is 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) is equivalent to cad['key']+=value Of course, it is just equivalent and cannot be done like this

Since the bottom layer uses

new

_value = value + delta

, then when value is 'a', it is also possible, as long as + can be used

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

Cache version: VERSION can pass in the same key, but save different values, implemented through version

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) Similarly, value supports +-

decr_version('key',value)

But it is not recommended to use str directly, etc. It is not recommended to use your own class

But when you really need to use a custom class to fill in version, the methods that need to be rewritten are (python3.x)

str

add

sub

The above is the detailed content of Detailed explanation of how Django transfers temporary data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template