Django Signal
Django internally provides a "signal strength" processing mechanism, a simple understanding is that when Django after receiving a request to do certain internal operations before the signal, to remind some recipients or do the operation, the benefit is to facilitate the program to customize the small function plug-in, but also the framework of its own a node-lotus operation
1) Django built-in signal
model signals pre_init # django modal automatic trigger before executing its construction method post_init # When Django's modal executes its construction method, it automatically triggers pre_save # django modal objects are automatically triggered before they are saved post_save # The Django modal object is saved and automatically triggered pre_delete Auto Trigger post_delete before # django modal object is deleted # django Modal object is deleted, auto trigger m2m_changed &nbsAutomatically trigger before and after the third table (Add,remove,clear) in the modal field of P; # django class_prepared # when the program starts, Detects registered apps in the modal class, and automatically triggers management signals pre_migrate for each class # automatically triggers post_ before executing the migrate command migrate # the request is triggered automatically after executing the migrate command /response signals request_started Auto Trigger request_finished before # request arrives After the # request finishes, automatically triggers the got_request_exception # request exception and automatically triggers the test signals setting_changed # automatically triggers when a configuration file is modified using test tests template_rendered # when the render template is tested with test, the database is automatically triggered Wrappers connection_created # When you create a database connection, Automatic triggering
2) Signal usage
The use of the Django signal only needs to import the trust module we need, for example, we take a database to save the trigger signal.
URL to create a new test page
urlpatterns = [url (r ' ^signal/$ ', views.signal),]
App Sibling directory new sg.py file
need to import the modules we need before using from django.core.signals import request_finishedfrom Django.core.signals import request_startedfrom django.core.signals import got_request _exceptionfrom django.db.models.signals import class_preparedfrom django.db.models.signals import pre_init, post_initfrom django.db.models.signals import pre_save, post_savefrom django.db.models.signals import pre_delete, post_deletefrom Django.db.models.signals import m2m_changedfrom django.db.models.signals import pre_ migrate, post_migratefrom django.test.signals import setting_changedfrom django.test.signals import template_renderedfrom django.db.backends.signals import connection_created // defines the signal function def f1 (Sender, **kwargs): print ("Signal_callback") // Registration LetterNumber Pre_save.connect (F1)
Views View function
Ready to connect the database before testing from APP01 import models//the views function def signal (reuqest): obj = models. Userinf (user= ' root ') print (' has create a data ... ') obj.save () obj = models. Userinf (user= ' root ') Obj.save () return HttpResponse (' OK ')
Here, Django performed three signal functions for us.
650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M02/8E/A8/wKiom1jIABSxWnv1AAC1QDzY-c0963.png "title=" 1.png "alt=" Wkiom1jiabsxwnv1aac1qdzy-c0963.png "/>
Custom Signal
If we feel that the built-in signal functions provided to us by Django are not sufficient for our development needs, we can also customize the signal
1) inside the SG file
Define the signal import Django.dispatchpizza_done = django.dispatch.Signal (providing_args=["toppings", "size"])//Register Signal def Callback (sender, **kwargs): Print ("callback") print (Sender,kwargs) Pizza_done.connect (callback)
2) in Views view file
From SG import Pizza_done def signal (reuqest): obj = models. Userinf (user= ' root ') obj.save ()//Trigger signal Pizza_done.send (sender= "Asdfasdf", toppings=123, size=456) return Htt Presponse (' OK ')
3) Execution Results
650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M01/8E/A7/wKioL1jIAADyMf-kAADTZXxafBk384.png "title=" 2.png "alt=" Wkiol1jiaadymf-kaadtzxxafbk384.png "/>
Cache
Django program in the face of a large number of accesses, if it involves database operations, will inevitably increase the burden of the database, query speed has serious impact; The simplest solution is to use the cache, the cache will be a view of the return value in memory or Memcache, in 5 minutes if someone comes to visit, Instead of performing the views operation, it takes the data directly from the cache and returns it to the user.
6 ways of caching are available within Django
Development Debug//Memory//File//Database//Memcache cache (python-memcached module)//memcache cache (PYLIBMC module)
We tested the Django cache usage using file as cache media.
1) New URL
urlpatterns = [url (r ' ^cache/$ ', Views.cache),]
2) Setting set cache
CACHES = {' default ': {' backend ': ' Django.core.cache.backends.filebased.FileBasedCache ',//Set file storage location ' Location ': Os.path.join (base_dir, ' Cache ')}}
3) Views View function
DEF cache (Request): Import Time CTime = Time.time () return render (Request, ' cache.html ', {' CTime ': CTime})
4) References in template files
{% Load cache%}<body>
5) Add cache adorner to specific views function
Cache Adorner @cache_page () def cache (Request): Import Time CTime = Time.time () return render (Request, ' cache.html ', { ' CTime ': CTime})
Page results
650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/8E/A8/wKiom1jH_--gnw5PAAFOfb0B8fU122.png "title=" 3.png "alt=" Wkiom1jh_--gnw5paafofb0b8fu122.png "/>
Other cache configurations
1) Development test
This is to start debugging with, the actual internal does not do any operation// configuration: caches = { ' Default ': { ' backend ': ' Django.core.cache.backends.dummy.DummyCache ', # engine ' TIMEOUT ': 300, Cache time-out (default 300,none means never expires, 0 means immediate expiration) ' OPTIONS ':{ ' Max_entries ': 300, # Maximum cache count (default) ' cull_frequency ': 3, # cache reaches the maximum number, the ratio of the number of cache is rejected, i.e.: 1/cull_frequency (default 3) }, ' Key_prefix ': ', # cache key prefix (default null) ' VERSION ': 1, # Cache Key's version (default 1) ' key_function ' function names # functions that generate KEY (the default function is generated as: "Prefix: Version: Key ") } } // Custom Keydef default_key_func (key, key_prefix, version): "" " default&nBsp;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:%s ' % (key_prefix, version, key) def get_key_func (key_func): "" " function to decide which key function to use. defaults 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
2) Memory
CACHES = {' default ': {' backend ': ' Django.core.cache.backends.locmem.LocMemCache ', ' Location ': ' Unique-snowflake ',}}
3) database
Note To execute Python manager.py makemigrations//python manager/py migratecaches = {' default ': {' backend ' : ' Django.core.cache.backends.db.DatabaseCache ', ' Location ': ' My_cache_table ', # database table}}
4) memcache cache (python-memcached module)
This cache uses the Python-memcached module to connect memcache caches = { ' Default ': { ' backend ': ' Django.core.cache.backends.memcached.MemcachedCache ', ' location ': ' 127.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 ': [ ' 172.19.26.240:11211 ', ' 172.19.26.242:11211 ', ] } }
5) Memcache cache (PYLIBMC module)
This cache uses the PYLIBMC module to connect memcache caches = { ' default ': { ' backend ': ' Django.core.cache.backends.memcached.PyLibMCCache ', ' location ': ' 127.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 ': [ ' 172.19.26.240:11211 ', ' 172.19.26.242:11211 ', ] }}
Caching Global Apps
Using middleware, after a series of authentication and other operations, if the content exists in the cache, then use Fetchfromcachemiddleware to get the content and return to the user, before returning to the user, to determine whether the cache already exists, If it does not exist, Updatecachemiddleware will save the cache to the cache, thereby achieving a full-station cache middleware = [' django.middleware.cache.UpdateCacheMiddleware ',//its He middleware ... ' Django.middleware.cache.FetchFromCacheMiddleware ',] Cache_middleware_alias = "" Cache_middleware_seconds = "cache_ Middleware_key_prefix = ""
This article comes from the "change from every day" blog, so be sure to keep this source http://lilongzi.blog.51cto.com/5519072/1906557
Django signal, cache operation for the automated Operations Python series