Django 缓存与信号

2018-07-19  本文已影响0人  vckah

缓存

缓存会在响应头中加一个字段:
Cache-Control: max-age=5

Expires 首部字段也可以用于告知缓存服务器该资源什么时候会过期。
在 HTTP/1.1 中,会优先处理 max-age 指令;
在 HTTP/1.0 中,max-age 指令会被忽略掉。

缓存方式有 5 种,包括:

 CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}
 CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '保存文件的位置',
    }
}
 CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table', # 数据库表
    }
}
之后执行创建表命令 python manage.py createcachetable
@cache_page(10)    # 缓存 10 秒
def view(request):
    pass

也可以在 url 种缓存

from django.views.decorators.cache import cache_page
urlpatterns = [
    path('foo/<int:code>/', cache_page(60 * 15)(my_view)),
]
{% load cache %}
以下是缓存的 html
{% cache 5 缓存key %}  5 秒
    <h1></h1>
{% endcache %}
django.middleware.cache.UpdateCacheMiddleware  --> 只有 process_response
xxx 其他中间件
django.middleware.cache.FetchFromCacheMiddleware --> 只有 process_request

信号

Django 包含一个“信号调度程序”,它有助于在框架中的其他位置发生操作时通知分离的应用程序。简而言之,信号允许某些发送者通知一组接收器已经发生了某些动作。当许多代码可能对同一事件感兴趣时,它们特别有用。
在用户注册后,保存密码到数据库中

# signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model

User = get_user_model()

@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        password = instance.password
        instance.set_password(password)
        instance.save()

然后在 apps.py 中设置:

class UsersConfig(AppConfig):
    def ready(self):
        import users.signals

Django 信号分类

Django信号其实是观察者模式

from django.db.backends.signals import pre_save

def callback(sender, *kwargs):
        pass

pre_save.connect(callback,sender=<model 的名字>)
这里 model 的名字可以不指定
那么就意味着所有 model 保存时都会触发

另外还可以自定义信号,不过需要自己指定发送信号,详情见官方文档

上一篇 下一篇

猜你喜欢

热点阅读