Python path [Chapter 2]: Django cache, signal, pythondjango

Source: Internet
Author: User

Python path [Chapter 2]: Django cache, signal, pythondjango
Cache

Since Django is a dynamic website, each request will perform corresponding operations on the Data. When the access volume of the program is large, the time consumption will inevitably become more obvious. The simplest solution is to use: cache, the cache saves the return value of a view to the memory or memcache. When someone accesses the view within five minutes, the operation in the view is not executed, instead, get the cached content directly from the memory or Redis and return

Django provides six caching methods:

  • Development and debugging
  • Memory
  • File
  • Database
  • Memcache cache (python-memcached module and pylibmc module)

1. Configuration

① Development Configuration

# This is used to start debugging. No operation is performed internally. # configuration: CACHES = {'default': {'backend': 'django. core. cache. backends. dummy. dummyCache ', # Engine 'timeout': 300, # cache TIMEOUT time (300 by default, None indicates never expiration, 0 indicates immediate expiration) 'options': {'max _ entries ': 300, # maximum number of caches (300 by default) 'ull _ FREQUENCY ': 3, # After the cache reaches the maximum number, remove the proportion of the number of caches, that is: 1/CULL_FREQUENCY (default: 3)}, 'key _ prefix': '', # cache key prefix (default: NULL) 'version': 1, # cache key version (default: 1) 'key _ function' FUNCTION name # generate the key function (default FUNCTION will generate: [Prefix: Version: key ])}} # custom key def default_key_func (key, key_prefix, version): "Default function to generate keys. constructs the key used by all other methods. by default it prepends the 'key _ prefix '. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. "return '% s: % s' % (key_prefix, version, key) def get_key_func (key_func):" Function to decide which key function to use. ults to ''default _ key_func ''. "if key_func is not None: if callable (key_func): return key_func else: return import_string (key_func) return default_key_func
Development

② Memory configuration

# This cache saves the content to the memory variable # configuration: CACHES = {'default': {'backend': 'django. core. cache. backends. locmem. locMemCache ', 'location': 'unique-snowflake', }}# Note: Other configurations are in the same development and debugging version.
Memory

③ File configuration

# This cache saves the content to the file # configuration: CACHES = {'default': {'backend': 'django. core. cache. backends. filebased. fileBasedCache ', 'location':'/var/tmp/django_cache ', }}# Note: Other configurations are in the same development and debugging version.
File

④ Database Configuration

# This cache saves the content to the database # configuration: CACHES = {'default': {'backend': 'django. core. cache. backends. db. databaseCache ', 'location': 'My _ cache_table', # Database Table }}# Note: run the create table command python manage. py createcachetable
Database

⑤ Memcache cache (python-memcached Module)

CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. memcachedCache ', 'location': '2017. 0.0.1: 11211 ',} CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. memcachedCache ', 'location': 'unix:/tmp/memcached. sock ',} CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. memcachedCache ', 'location': ['123. 19.26.240: 11211 ', '2017. 19.26.242: 11211 ',]} CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. memcachedCache ', 'location': [# weight ('100. 172. 19.26.240: 11211 ', 1), ('2017. 19.26.242: 11211 ', 15)]}
Python-memcached Module

⑥ Memcache cache (pylibmc module)

# This cache uses the pylibmc module to connect to memcache CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. pyLibMCCache ', 'location': '2017. 0.0.1: 11211 ',} CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. pyLibMCCache ', 'location':'/tmp/memcached. sock ',} CACHES = {'default': {'backend': 'django. core. cache. backends. memcached. pyLibMCCache ', 'location': ['2017. 19.26.240: 11211 ', '2017. 19.26.242: 11211 ',]}
Pylibmc Module

2. Application

① Full-site use

Middleware is used to perform a series of authentication and other operations. If the content exists in the cache, FetchFromCacheMiddleware is used to obtain the content and return it to the user. before returning it to the user, determine whether the cache already exists, if it does not exist, UpdateCacheMiddleware saves the cache to the cache, so that the full-site cache MIDDLEWARE = [# Write to the top 'django. middleware. cache. updateCacheMiddleware ', # other middleware... # Write to the bottom 'django. middleware. cache. fetchFromCacheMiddleware ',]
Global Effect

② Separate View cache

Method 1: from django. views. decorators. cache import cache_page @ cache_page (60*15) def my_view (request ):... method 2: from django. views. decorators. cache import cache_page urlpatterns = [url (R' ^ foo/([0-9] {1, 2})/$ ', cache_page (60*15) (my_view),]
Independent method takes effect

③ Use the local view

A. Import TemplateTag {% load cache %} B. Use cache {% cache 5000 cache key %} cache content {% endcache %}
Html takes effect separately

 

3. Separate View cache example

All requests processed by the cache method are cached for 10 seconds.

HTML file:

<!DOCTYPE html>Cache.html

Configuration file:

CACHES = {    'default': {        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',        'LOCATION': os.path.join(BASE_DIR,'cache'),    }}
Settings. py

Process files:

From django. views. decorators. cache import cache_page @ cache_page (10) # describe the cache method def cache (request): import time ctime = time. time () return render(request,'cache.html ', {'ctime': ctime })

 

4. Local View Example

Cache a part of an html file

HTML file:

{% Load cache %} <! DOCTYPE html> Cache.html

Configuration file:

CACHES = {    'default': {        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',        'LOCATION': os.path.join(BASE_DIR,'cache'),    }}
Settings. py

Process files:

def cache(request):    import time    ctime = time.time()    return render(request,'cache.html',{'ctime':ctime})

 

5. Global effectiveness 

Configuration file:

MIDDLEWARE = [    'django.middleware.cache.UpdateCacheMiddleware',    'django.middleware.security.SecurityMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',    'django.middleware.cache.FetchFromCacheMiddleware',]
Settings. py

The rest of the files are consistent, with a high global priority. The request process --> uses middleware and performs a series of authentication operations. If the content exists in the cache, FetchFromCacheMiddleware is used to obtain the content and return it to the user, if this parameter does not exist, go down and execute the views function. After the result, the UpdateCacheMiddleware will save the cache to implement full-site cache.

 

Signal

Django provides "signal scheduling" for decoupling when the framework executes operations. In general, when some actions occur, the signal allows specific senders to remind some recipients.

1. Django built-in Signal

Model signals pre_init # Before django's modal executes its constructor method, it automatically triggers post_init # django's modal to execute its constructor, and triggers pre_save # Before django's modal object is saved, after the post_save # django modal object is automatically triggered and saved, the pre_delete # django modal object is automatically triggered. After the post_delete # django modal object is deleted, automatically trigger m2m_changed # before and after the third table (add, remove, clear) using the m2m field in django modal, automatically trigger class_prepared # When the program is started, detects modal classes in registered apps. For each class, the Management signals pre_migrate is automatically triggered. # After the migrate command is executed, the post_migrate is automatically triggered. # After the migrate command is executed, automatically trigger Request/response signals request_started # automatically trigger request_finished # after the Request ends, automatically trigger got_request_exception # after the Request is abnormal, test signals setting_changed # template_rendered is automatically triggered when you use test to modify the configuration file # When you use test to Test the rendering template, Database Wrappers connection_created is automatically triggered # When you create a Database connection

Built-in signal call method:

from django.core.signals import request_finished    from django.core.signals import request_started    from django.core.signals import got_request_exception    from django.db.models.signals import class_prepared    from django.db.models.signals import pre_init, post_init    from django.db.models.signals import pre_save, post_save    from django.db.models.signals import pre_delete, post_delete    from django.db.models.signals import m2m_changed    from django.db.models.signals import pre_migrate, post_migrate    from django.test.signals import setting_changed    from django.test.signals import template_rendered    from django.db.backends.signals import connection_created
Built-in signal call

 

2. built-in signal registration function

For built-in signals, you need to register and execute functions in the signals during use. When the program executes the corresponding operations, the registration function is automatically triggered:

Create the file sg. py and register the function:

# Sg. pyfrom django. db. models. signals import pre_initdef f1 (sender, ** kwargs): print ("before the constructor is executed") print (sender, kwargs) pre_init.connect (f1) # Before running the construction method of django modal, automatic triggering can be any

_ Init _. py:

import sg

Process file views. py:

from app01 import modelsdef signal(request):    obj1 = models.UserInfo.objects.create(user="root")    print('obj1')    obj2 = models.UserInfo.objects.create(user="root")    print('obj2')    return HttpResponse("OK")
Before the constructor is executed, obj1 before the constructor is executed.
Print

 

3. Custom Signal

Definition signal:

Import django. dispatchpizza_done = django. dispatch. Signal (providing_args = ["toppings", "size"]) # toppings, size parameters to be input

Registration signal:

def callback(sender, **kwargs):    print("callback")    print(sender,kwargs) pizza_done.connect(callback)

Trigger Signal:

From path import pizza_done pizza_done.send (sender = 'seven', toppings = 123, size = 456)

Because the built-in signal trigger has been integrated into Django, it will be called automatically. For custom signals, developers need to trigger them at any location.

 

Related Article

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.