zoukankan      html  css  js  c++  java
  • django中的缓存

    对于一个动态网站来说,用户的每次访问都意味着对服务器的一次开销,当该服务器的并发访问非常大时,对于一个动态网站来说,开销会非常的大。所以对于大中型web应用来说,减轻服务器的性能瓶颈就很有必要

    对于django来说,cache就提供了一种解决方式

    通俗的讲,缓存就是把一些非敏性,对实时性要求不高的数据从我们的后台数据库取到数据后,将之保存到文件或内存或者我们的一轻高性能的中间件系统中,当用户再次请求时,将直接从中间件或者文件,内存中取出该 数据,将不再对数据库或其它关键应用再次请求以缓解对流量对性能造成的影响

    在django中支持的缓存方式有:内存缓存,数据库缓存,文件缓存以及memcache缓存和虚拟缓存(仅用于开发时)

    在实际的应用中常用的方式有:内存缓存,文件缓存,以及memcache缓存

    对于使用不同的cache模块,需要在settings.py中文件中做不同的配置,以文件缓存为例

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

    }
    }

    在django中缓存可以在Views视图处理函数中与templates中使用,如下所示:

    import time

    from django.http import HttpResponse
    from django.shortcuts import render
    from django.views.decorators.cache import cache_page
    from django.core.cache import cache

    def cachedemo1(request):
    t=time.time()
    return render(request, 'app02/cachedemo.html', {'time':t})
    在以上代码中返回了一个时间戳
    在相应的html文件中的代码如下所示:


    {% load cache %}
    {% cache 10 c %}
    {{ time }}
    {% endcache %}

    要在页面中使用缓存,必须在页面中使用标签{% load cache %}的方式导入cache

    {% cache 10 c %}
    {{ time }}
    {% endcache %}
    以上代码的功能便是,在一个名为c的缓存块中将{{time}}的值缓存10秒钟

    如果要在视图中应用缓存的话,需要在视图中使用cache_page(10)装饰器,10为时间,默认为秒

    如下所示:

    @cache_page(10)
    def cachedemo1(request):
    t=time.time()
    return render(request, 'app02/cachedemo.html', {'time':t})


    使用硬编码方式使用cache

    def add_CacheByhardCode(key,value,timeout):
    '''
    使用add方法添加cache
    :param key:
    :param value:
    :param timeout:
    :return:
    '''
    cache.add(key=key,value=value,timeout=timeout)
    return True
    def set_CacheByhardCode(key,value,timeout):
    cache.set(key=key,value=value,timeout=timeout)
    return True
    def has_cache(key):
    obj=cache.has_key(key=key)
    return obj
    def delete_cache(key):
    cache.delete(key=key)
    return True
    def get_or_set_cache(key,value,timeout):
    cache.get_or_set(key=key,default=value,timeout=timeout)
    return True
    def get_CacheByKey(key):
    obj=cache.get(key)
    return obj

    def setCacheByHardCode(request):
    #isok=add_CacheByhardCode('username','hello',10)
    isok=get_or_set_cache('username','hello world',10)
    if isok:
    username=get_CacheByKey('username')
    print(username)
    if username:
    return render(request, 'app02/cachedemo.html', {'username':username})
    return HttpResponse('ok')




  • 相关阅读:
    ARTS第十一周
    ARTS第十周
    ARTS第九周
    一.Java技术现象
    ARTS第八周
    2019书单
    10.枚举的使用
    9.文件输入与输出
    软件模块化设计
    8.String API
  • 原文地址:https://www.cnblogs.com/lijintian/p/8819765.html
Copyright © 2011-2022 走看看