当前位置: 首页 > 软件库 > 数据库相关 > >

django-cacheops

授权协议 BSD-3-Clause License
开发语言 JavaScript
所属分类 数据库相关
软件类型 开源软件
地区 不详
投 递 者 江正德
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Cacheops

A slick app that supports automatic or manual queryset caching and automaticgranular event-driven invalidation.

It uses redis as backend for ORM cache and redis orfilesystem for simple time-invalidated one.

And there is more to it:

  • decorators to cache any user function or view as a queryset or by time
  • extensions for django and jinja2 templates
  • transparent transaction support
  • dog-pile prevention mechanism
  • a couple of hacks to make django faster

Requirements

Python 3.5+, Django 2.1+ and Redis 4.0+.

Installation

Using pip:

$ pip install django-cacheops

# Or from github directly
$ pip install git+https://github.com/Suor/django-cacheops.git@master

Setup

Add cacheops to your INSTALLED_APPS.

Setup redis connection and enable caching for desired models:

CACHEOPS_REDIS = {
    'host': 'localhost', # redis-server is on same machine
    'port': 6379,        # default redis port
    'db': 1,             # SELECT non-default redis database
                         # using separate redis db or redis instance
                         # is highly recommended

    'socket_timeout': 3,   # connection timeout in seconds, optional
    'password': '...',     # optional
    'unix_socket_path': '' # replaces host and port
}

# Alternatively the redis connection can be defined using a URL:
CACHEOPS_REDIS = "redis://localhost:6379/1"
# or
CACHEOPS_REDIS = "unix://path/to/socket?db=1"
# or with password (note a colon)
CACHEOPS_REDIS = "redis://:password@localhost:6379/1"

# If you want to use sentinel, specify this variable
CACHEOPS_SENTINEL = {
    'locations': [('localhost', 26379)], # sentinel locations, required
    'service_name': 'mymaster',          # sentinel service name, required
    'socket_timeout': 0.1,               # connection timeout in seconds, optional
    'db': 0                              # redis database, default: 0
    ...                                  # everything else is passed to Sentinel()
}

# To use your own redis client class,
# should be compatible or subclass cacheops.redis.CacheopsRedis
CACHEOPS_CLIENT_CLASS = 'your.redis.ClientClass'

CACHEOPS = {
    # Automatically cache any User.objects.get() calls for 15 minutes
    # This also includes .first() and .last() calls,
    # as well as request.user or post.author access,
    # where Post.author is a foreign key to auth.User
    'auth.user': {'ops': 'get', 'timeout': 60*15},

    # Automatically cache all gets and queryset fetches
    # to other django.contrib.auth models for an hour
    'auth.*': {'ops': {'fetch', 'get'}, 'timeout': 60*60},

    # Cache all queries to Permission
    # 'all' is an alias for {'get', 'fetch', 'count', 'aggregate', 'exists'}
    'auth.permission': {'ops': 'all', 'timeout': 60*60},

    # Enable manual caching on all other models with default timeout of an hour
    # Use Post.objects.cache().get(...)
    #  or Tags.objects.filter(...).order_by(...).cache()
    # to cache particular ORM request.
    # Invalidation is still automatic
    '*.*': {'ops': (), 'timeout': 60*60},

    # And since ops is empty by default you can rewrite last line as:
    '*.*': {'timeout': 60*60},

    # NOTE: binding signals has its overhead, like preventing fast mass deletes,
    #       you might want to only register whatever you cache and dependencies.

    # Finally you can explicitely forbid even manual caching with:
    'some_app.*': None,
}

You can configure default profile setting with CACHEOPS_DEFAULTS. This way you can rewrite the config above:

CACHEOPS_DEFAULTS = {
    'timeout': 60*60
}
CACHEOPS = {
    'auth.user': {'ops': 'get', 'timeout': 60*15},
    'auth.*': {'ops': ('fetch', 'get')},
    'auth.permission': {'ops': 'all'},
    '*.*': {},
}

Using '*.*' with non-empty ops is not recommendedsince it will easily cache something you don't intent to or even know about like migrations tables.The better approach will be restricting by app with 'app_name.*'.

Besides ops and timeout options you can also use:

local_get: True
To cache simple gets for this model in process local memory.This is very fast, but is not invalidated in any way until process is restarted.Still could be useful for extremely rarely changed things.
cache_on_save=True | 'field_name'
To write an instance to cache upon save.Cached instance will be retrieved on .get(field_name=...) request.Setting to True causes caching by primary key.

Additionally, you can tell cacheops to degrade gracefully on redis fail with:

CACHEOPS_DEGRADE_ON_FAILURE = True

There is also a possibility to make all cacheops methods and decorators no-op, e.g. for testing:

from django.test import override_settings

@override_settings(CACHEOPS_ENABLED=False)
def test_something():
    # ...
    assert cond

Usage

Automatic caching

It's automatic you just need to set it up.

Manual caching

You can force any queryset to use cache by calling its .cache() method:

Article.objects.filter(tag=2).cache()

Here you can specify which ops should be cached for the queryset, for example, this code:

qs = Article.objects.filter(tag=2).cache(ops=['count'])
paginator = Paginator(objects, ipp)
articles = list(pager.page(page_num)) # hits database

will cache count call in Paginator but not later articles fetch.There are five possible actions - get, fetch, count, aggregate and exists.You can pass any subset of this ops to .cache() method even empty - to turn off caching.There is, however, a shortcut for the latter:

qs = Article.objects.filter(visible=True).nocache()
qs1 = qs.filter(tag=2)       # hits database
qs2 = qs.filter(category=3)  # hits it once more

It is useful when you want to disable automatic caching on particular queryset.

You can also override default timeout for particular queryset with .cache(timeout=...).

Function caching

You can cache and invalidate result of a function the same way as a queryset.Cached results of the next function will be invalidated on any Article change,addition or deletion:

from cacheops import cached_as

@cached_as(Article, timeout=120)
def article_stats():
    return {
        'tags': list(Article.objects.values('tag').annotate(Count('id')))
        'categories': list(Article.objects.values('category').annotate(Count('id')))
    }

Note that we are using list on both querysets here, it's because we don't wantto cache queryset objects but their results.

Also note that if you want to filter queryset based on arguments,e.g. to make invalidation more granular, you can use a local function:

def articles_block(category, count=5):
    qs = Article.objects.filter(category=category)

    @cached_as(qs, extra=count)
    def _articles_block():
        articles = list(qs.filter(photo=True)[:count])
        if len(articles) < count:
            articles += list(qs.filter(photo=False)[:count-len(articles)])
        return articles

    return _articles_block()

We added extra here to make different keys for calls with same category but differentcount. Cache key will also depend on function arguments, so we could just pass count asan argument to inner function. We also omitted timeout here, so a default for the modelwill be used.

Another possibility is to make function cache invalidate on changes to any one of several models:

@cached_as(Article.objects.filter(public=True), Tag)
def article_stats():
    return {...}

As you can see, we can mix querysets and models here.

View caching

You can also cache and invalidate a view as a queryset. This works mostly the same way as functioncaching, but only path of the request parameter is used to construct cache key:

from cacheops import cached_view_as

@cached_view_as(News)
def news_index(request):
    # ...
    return render(...)

You can pass timeout, extra and several samples the same way as to @cached_as(). Note that you can pass a function as extra:

@cached_view_as(News, extra=lambda req: req.user.is_staff)
def news_index(request):
    # ... add extra things for staff
    return render(...)

A function passed as extra receives the same arguments as the cached function.

Class based views can also be cached:

class NewsIndex(ListView):
    model = News

news_index = cached_view_as(News, ...)(NewsIndex.as_view())

Invalidation

Cacheops uses both time and event-driven invalidation. The event-driven onelistens on model signals and invalidates appropriate caches on Model.save(), .delete()and m2m changes.

Invalidation tries to be granular which means it won't invalidate a querysetthat cannot be influenced by added/updated/deleted object judging by queryconditions. Most of the time this will do what you want, if it won't you can useone of the following:

from cacheops import invalidate_obj, invalidate_model, invalidate_all

invalidate_obj(some_article)  # invalidates queries affected by some_article
invalidate_model(Article)     # invalidates all queries for model
invalidate_all()              # flush redis cache database

And last there is invalidate command:

./manage.py invalidate articles.Article.34  # same as invalidate_obj
./manage.py invalidate articles.Article     # same as invalidate_model
./manage.py invalidate articles   # invalidate all models in articles

And the one that FLUSHES cacheops redis database:

./manage.py invalidate all

Don't use that if you share redis database for both cache and something else.

Turning off and postponing invalidation

There is also a way to turn off invalidation for a while:

from cacheops import no_invalidation

with no_invalidation:
    # ... do some changes
    obj.save()

Also works as decorator:

@no_invalidation
def some_work(...):
    # ... do some changes
    obj.save()

Combined with try ... finally it could be used to postpone invalidation:

try:
    with no_invalidation:
        # ...
finally:
    invalidate_obj(...)
    # ... or
    invalidate_model(...)

Postponing invalidation can speed up batch jobs.

Mass updates

Normally qs.update(...) doesn't emit any events and thus doesn't trigger invalidation.And there is no transparent and efficient way to do that: trying to act on conditions willinvalidate too much if update conditions are orthogonal to many queries conditions,and to act on specific objects we will need to fetch all of them,which QuerySet.update() users generally try to avoid.

In the case you actually want to perform the latter cacheops provides a shortcut:

qs.invalidated_update(...)

Note that all the updated objects are fetched twice, prior and post the update.

Simple time-invalidated cache

To cache result of a function call or a view for some time use:

from cacheops import cached, cached_view

@cached(timeout=number_of_seconds)
def top_articles(category):
    return ... # Some costly queries

@cached_view(timeout=number_of_seconds)
def top_articles(request, category=None):
    # Some costly queries
    return HttpResponse(...)

@cached() will generate separate entry for each combination of decorated function and itsarguments. Also you can use extra same way as in @cached_as(), most useful for nestedfunctions:

@property
def articles_json(self):
    @cached(timeout=10*60, extra=self.category_id)
    def _articles_json():
        ...
        return json.dumps(...)

    return _articles_json()

You can manually invalidate or update a result of a cached function:

top_articles.invalidate(some_category)
top_articles.key(some_category).set(new_value)

To invalidate cached view you can pass absolute uri instead of request:

top_articles.invalidate('http://example.com/page', some_category)

Cacheops also provides get/set primitives for simple cache:

from cacheops import cache

cache.set(cache_key, data, timeout=None)
cache.get(cache_key)
cache.delete(cache_key)

cache.get will raise CacheMiss if nothing is stored for given key:

from cacheops import cache, CacheMiss

try:
    result = cache.get(key)
except CacheMiss:
    ... # deal with it

File Cache

File based cache can be used the same way as simple time-invalidated one:

from cacheops import file_cache

@file_cache.cached(timeout=number_of_seconds)
def top_articles(category):
    return ... # Some costly queries

@file_cache.cached_view(timeout=number_of_seconds)
def top_articles(request, category):
    # Some costly queries
    return HttpResponse(...)

# later, on appropriate event
top_articles.invalidate(some_category)
# or
top_articles.key(some_category).set(some_value)

# primitives
file_cache.set(cache_key, data, timeout=None)
file_cache.get(cache_key)
file_cache.delete(cache_key)

It has several improvements upon django built-in file cache, both about high load.First, it's safe against concurrent writes. Second, it's invalidation is done as separate task,you'll need to call this from crontab for that to work:

/path/manage.py cleanfilecache
/path/manage.py cleanfilecache /path/to/non-default/cache/dir

Django templates integration

Cacheops provides tags to cache template fragments. They mimic @cached_asand @cached decorators, however, they require explicit naming of each fragment:

{% load cacheops %}

{% cached_as <queryset> <timeout> <fragment_name> [<extra1> <extra2> ...] %}
    ... some template code ...
{% endcached_as %}

{% cached <timeout> <fragment_name> [<extra1> <extra2> ...] %}
    ... some template code ...
{% endcached %}

You can use None for timeout in @cached_as to use it's default value for model.

To invalidate cached fragment use:

from cacheops import invalidate_fragment

invalidate_fragment(fragment_name, extra1, ...)

If you have more complex fragment caching needs, cacheops provides a helper tomake your own template tags which decorate a template fragment in a wayanalogous to decorating a function with @cached or @cached_as.This is experimental feature for now.

To use it create myapp/templatetags/mycachetags.py and add something like this there:

from cacheops import cached_as, CacheopsLibrary

register = CacheopsLibrary()

@register.decorator_tag(takes_context=True)
def cache_menu(context, menu_name):
    from django.utils import translation
    from myapp.models import Flag, MenuItem

    request = context.get('request')
    if request and request.user.is_staff():
        # Use noop decorator to bypass caching for staff
        return lambda func: func

    return cached_as(
        # Invalidate cache if any menu item or a flag for menu changes
        MenuItem,
        Flag.objects.filter(name='menu'),
        # Vary for menu name and language, also stamp it as "menu" to be safe
        extra=("menu", menu_name, translation.get_language()),
        timeout=24 * 60 * 60
    )

@decorator_tag here creates a template tag behaving the same as returned decoratorupon wrapped template fragment. Resulting template tag could be used as follows:

{% load mycachetags %}

{% cache_menu "top" %}
    ... the top menu template code ...
{% endcache_menu %}

... some template code ..

{% cache_menu "bottom" %}
    ... the bottom menu template code ...
{% endcache_menu %}

Jinja2 extension

Add cacheops.jinja2.cache to your extensions and use:

{% cached_as <queryset> [, timeout=<timeout>] [, extra=<key addition>] %}
    ... some template code ...
{% endcached_as %}

or

{% cached [timeout=<timeout>] [, extra=<key addition>] %}
    ...
{% endcached %}

Tags work the same way as corresponding decorators.

Transactions

Cacheops transparently supports transactions. This is implemented by following simple rules:

  1. Once transaction is dirty (has changes) caching turns off. The reason is that the state of database at this point is only visible to current transaction and should not affect other users and vice versa.
  2. Any invalidating calls are scheduled to run on the outer commit of transaction.
  3. Savepoints and rollbacks are also handled appropriately.

Mind that simple and file cache don't turn itself off in transactions but work as usual.

Dog-pile effect prevention

There is optional locking mechanism to prevent several threads or processes simultaneously performing same heavy task. It works with @cached_as() and querysets:

@cached_as(qs, lock=True)
def heavy_func(...):
    # ...

for item in qs.cache(lock=True):
    # ...

It is also possible to specify lock: True in CACHEOPS setting but that would probably be a waste. Locking has no overhead on cache hit though.

Multiple database support

By default cacheops considers query result is same for same query, not dependingon database queried. That could be changed with db_agnostic cache profile option:

CACHEOPS = {
    'some.model': {'ops': 'get', 'db_agnostic': False, 'timeout': ...}
}

Sharing redis instance

Cacheops provides a way to share a redis instance by adding prefix to cache keys:

CACHEOPS_PREFIX = lambda query: ...
# or
CACHEOPS_PREFIX = 'some.module.cacheops_prefix'

A most common usage would probably be a prefix by host name:

# get_request() returns current request saved to threadlocal by some middleware
cacheops_prefix = lambda _: get_request().get_host()

A query object passed to callback also enables reflection on used databases and tables:

def cacheops_prefix(query):
    query.dbs    # A list of databases queried
    query.tables # A list of tables query is invalidated on

    if set(query.tables) <= HELPER_TABLES:
        return 'helper:'
    if query.tables == ['blog_post']:
        return 'blog:'

NOTE: prefix is not used in simple and file cache. This might change in future cacheops.

Custom serialization

Cacheops uses pickle by default, employing it's default protocol. But you can specify your ownit might be any module or a class having .dumps() and .loads() functions. For example you can use dill instead, which can serialize more things like anonymous functions:

CACHEOPS_SERIALIZER = 'dill'

One less obvious use is to fix pickle protocol, to use cacheops cache across python versions:

import pickle

class CACHEOPS_SERIALIZER:
    dumps = lambda data: pickle.dumps(data, 3)
    loads = pickle.loads

Using memory limit

If your cache never grows too large you may not bother. But if you do you have some options.Cacheops stores cached data along with invalidation data,so you can't just set maxmemory and let redis evict at its will.For now cacheops offers 2 imperfect strategies, which are considered experimental.So be careful and consider leaving feedback.

First strategy is configuring maxmemory-policy volatile-ttl. Invalidation data is guaranteed to have higher TTL than referenced keys.Redis however doesn't guarantee perfect TTL eviction order, it selects several keys and removesone with the least TTL, thus invalidator could be evicted before cache key it refers leaving it orphan and causing it survive next invalidation.You can reduce this chance by increasing maxmemory-samples redis config option and by reducing cache timeout.

Second strategy, probably more efficient one is adding CACHEOPS_LRU = True to your settings and then using maxmemory-policy volatile-lru.However, this makes invalidation structures persistent, they are still removed on associated events, but in absence of them can clutter redis database.

Keeping stats

Cacheops provides cache_read and cache_invalidated signals for you to keep track.

Cache read signal is emitted immediately after each cache lookup. Passed arguments are: sender - model class if queryset cache is fetched,func - decorated function and hit - fetch success as boolean value.

Here is a simple stats implementation:

from cacheops.signals import cache_read
from statsd.defaults.django import statsd

def stats_collector(sender, func, hit, **kwargs):
    event = 'hit' if hit else 'miss'
    statsd.incr('cacheops.%s' % event)

cache_read.connect(stats_collector)

Cache invalidation signal is emitted after object, model or global invalidation passing sender and obj_dict args. Note that during normal operation cacheops only uses object invalidation, calling it once for each model create/delete and twice for update: passing old and new object dictionary.

CAVEATS

  1. Conditions other than __exact, __in and __isnull=True don't make invalidationmore granular.
  2. Conditions on TextFields, FileFields and BinaryFields don't make it either.One should not test on their equality anyway. See CACHEOPS_SKIP_FIELDS though.
  3. Update of "selected_related" object does not invalidate cache for queryset.Use .prefetch_related() instead.
  4. Mass updates don't trigger invalidation by default. But see .invalidated_update().
  5. Sliced queries are invalidated as non-sliced ones.
  6. Doesn't work with .raw() and other sql queries.
  7. Conditions on subqueries don't affect invalidation.
  8. Doesn't work right with multi-table inheritance.

Here 1, 2, 3, 5 are part of the design compromise, trying to solve them will makethings complicated and slow. 7 can be implemented if needed, but it'sprobably counter-productive since one can just break queries into simpler ones,which cache better. 4 is a deliberate choice, making it "right" will flushcache too much when update conditions are orthogonal to most queries conditions,see, however, .invalidated_update(). 8 is postponed until it will gainmore interest or a champion willing to implement it emerges.

All unsupported things could still be used easily enough with the help of @cached_as().

Performance tips

Here come some performance tips to make cacheops and Django ORM faster.

  1. When you use cache you pickle and unpickle lots of django model instances, which could be slow. You can optimize django models serialization with django-pickling.

  2. Constructing querysets is rather slow in django, mainly because most of QuerySet methods clone self, then change it and return the clone. Original queryset is usually thrown away. Cacheops adds .inplace() method, which makes queryset mutating, preventing useless cloning:

    items = Item.objects.inplace().filter(category=12).order_by('-date')[:20]

    You can revert queryset to cloning state using .cloning() call.

    Note that this is a micro-optimization technique. Using it is only desirable in the hottest places, not everywhere.

  3. Use template fragment caching when possible, it's way more fast because you don't need to generate anything. Also pickling/unpickling a string is much faster than a list of model instances.

  4. Run separate redis instance for cache with disabled persistence. You can manually call SAVE or BGSAVE to stay hot upon server restart.

  5. If you filter queryset on many different or complex conditions cache could degrade performance (comparing to uncached db calls) in consequence of frequent cache misses. Disable cache in such cases entirely or on some heuristics which detect if this request would be probably hit. E.g. enable cache if only some primary fields are used in filter.

    Caching querysets with large amount of filters also slows down all subsequent invalidation on that model. You can disable caching if more than some amount of fields is used in filter simultaneously.

Writing a test

Writing a test for an issue you are experiencing can speed up its resolution a lot.Here is how you do that. I suppose you have some application code causing it.

  1. Make a fork.
  2. Install all from requirements-test.txt.
  3. Ensure you can run tests with ./run_tests.py.
  4. Copy relevant models code to tests/models.py.
  5. Go to tests/tests.py and paste code causing exception to IssueTests.test_{issue_number}.
  6. Execute ./run_tests.py {issue_number} and see it failing.
  7. Cut down model and test code until error disappears and make a step back.
  8. Commit changes and make a pull request.

TODO

  • faster .get() handling for simple cases such as get by pk/id, with simple key calculation
  • integrate previous one with prefetch_related()
  • shard cache between multiple redises
  • respect subqueries?
  • respect headers in @cached_view*?
  • group invalidate_obj() calls?
  • a postpone invalidation context manager/decorator?
  • fast mode: store cache in local memory, but check in with redis if it's valid
  • an interface for complex fields to extract exact on parts or transforms: ArrayField.len => field__len=?, ArrayField[0] => field__0=?, JSONField['some_key'] => field__some_key=?
  • custom cache eviction strategy in lua
  • cache a string directly (no pickle) for direct serving (custom key function?)
  • Django中的cached_property通过属性描述符实现 属性描述符:实现了特定协议的类,这个协议包括 __get__、 __set__ 和 __delete__ 方法。描述符的用法是,创建一个实例,作为另一个类的类属性 import datetime class cached_property(object): """ Decorator that converts

  • 下面的伪代码演示了如何对动态页面的结果进行缓存: given a URL, try finding that page in the cache if the page is in the cache: return the cached page else: generate the page save the generated page in the cache (for next time

  • 首先安装下载安装 pip install django-redis。 下载完成后,打开settings.py中配置django cache CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379",

  • 缓存简介 在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增,删,查,改,渲染模板,执行业务逻辑,最后生成用户看到的页面. 当一个网站的用户访问量很大的时候,每一次的的后台操作,都会消耗很多的服务端资源,所以必须使用缓存来减轻后端服务器的压力. 缓存是将一些常用的数据保存到内存或者memcache中,在一定的时间内有人来访问这些数据时,则不再去执行数据库及渲染等操作,而是直接从内存或m

  • 转自: 出处 针对数据编码实现: from django.core.cache import cache #存储缓存数据 cache.set('cache_key',data,60*15)#cache_key为存储在缓存中的唯一值,data为存储的数据,60*15为缓存数据的时间 #获取缓存数据 cache.get('cache_key',None)#cache_key为储存缓

  • class cached_property(object): """ Decorator that converts a method with a single self argument into a property cached on the instance. Optional ``name`` argument allows you to make c

  • 缓存:提升服务器响应速度 Django内置缓存框架 使用数据库进行缓存:命令行输入 【缓存里如果信息存在将返回给客户端,如果没有将去Models查询,然后Models要和数据库对接,然后返回models 然后再返给views,views要进行存储然后再一次返回给客户端】 【使用数据库做缓存会自动生成my_cache_table表】 @cache_page:是装饰器的意思 1、创建缓存表名字:pyt

  • 1.设定cache cache可以设定为3中级别:数据库,文件,内存。 设定cache可以在setting.py中修改CACHE_BACKEND变量来修改。 2. 安装Memcached 毋庸置疑memory cache是最快的缓存了。安装相关步骤如下: 1)安装Memcached 网站:http://danga.com/memcached/ 2)安装Memcached Python bindin

  •   应用名/views.py(视图,cache,缓存数据): from django.shortcuts import render from django.views.generic import View from django.core.cache import cache # 导入缓存 # 类视图 (缓存数据库中的数据) class IndexView(View): '''

  • 一、服务器缓存策略 缓存定义:缓存是一类可以更快的读取数据的介质统称,也指其他可以加快数据读取的存储方式。一般用来存储临时数据,常用介质的是读取速度很快的内存 意义:视图渲染有一定的成本,数据库的频繁查询过高,所以对低频变动的页面可以考虑使用缓存技术,减少实际渲染次数,用户拿到响应的时间成本会更低 缓存利用场景: (1)博客列表页 (2)电商商品详情页 场景特点:缓存的地方,数据变动频率较少 1、

  • 需求:将首页的一部分内容缓存下来,第二次访问时从缓存中取得,减少数据库的压力,减少响应时间,优化用户体验 django 提供了视图缓存、前端模板缓存,以及站点缓存 上述缓存效率不高,本次利用 cache api 来解决相关需求 def index(reuqest): # 所有博客类型 if cache.get("blog_types"): # 如果博客类型在缓存中,就从缓

  • memcache 可以缓存一切可序列化和反序列化的对象 python-memcached使用pickle和cpickle来序列化和反序列化对象 而pickle可以序列化的类型有 The following types can be pickled: None, True, and False integers, long integers, floating point numbers, comp

  • 缓存的使用 HTTP 请求通常是数据库链接,数据处理,和模板渲染的。就处理数据而言,它的开销可比服务一个静态网站大多了。 请求开销在你的网站有越来越多的流量时是有意义的。这也使得缓存变得很有必要。通过缓存 HTTP 请求中 的查询结果,计算结果,或者是渲染上下文,你将会避免在接下来的请求中巨大的开销。这使得服务端的响应时间和处理时间变短。 Django 配备有一个健硕的缓存系统,这使得你可以使用不

  • 1 缓存配置 1.1 将缓存的数据存储到您的数据库中: 说明:尽管存储介质没有更换,但是当把一次负责查询的结果直接存储到表里,比如多个条件的过滤查询结果,可避免重复进行复杂查询,提升效率。 配置: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',

  • 前言 由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显 缓存将一个某个views的返回值保存至内存或者memcache中,5分钟内再有人来访问时,则不再去执行view中的操作 而是直接从内存或者Redis中之前缓存的内容拿到,并返回 Django自带的缓存 1.开发调试缓存 # 开发调试缓存(虽然配置上,但实际没有缓存,还是到数据库取) CA

  • 安装依赖测试环境 ubantu环境下安装依赖 sudo apt-get install libmemcached-dev 安装(虚拟环境) pip install django-pylibmc 查看安装包的结果 pip freeze > requirements.txt 执行python manage.py shell进入django的python环境   测试memcache安装是否成功。 >>

 相关资料
  • PyCharm的一个特性是它包含对Django的支持。 能够在PyCharm中包含JavaScript功能,它可以被认为是Django的最佳IDE。 在PyCharm IDE中创建Django项目的基本步骤如下 - 如果启用了EnableDjangoadmin选项,PyCharm将为您设置管理站点。 模板调试 调试适用于Django和Jinja模板。 我们可以检查变量,逐步执行代码,并在调试器中执

  • Django 是一个高级 Python Web 框架,鼓励快速开发和简洁实用的设计。Django 使你可以更轻松地以更少的代码更快地构建更好的 Web 应用程序。 Django 框架的核心组件有: 用于创建模型的对象关系映射 为最终用户设计的完美管理界面 一流的 URL 设计 设计者友好的模板语言 缓存系统 示例代码: from django.template import Context, lo

  • 问题内容: 我想知道是否有人将Django REST框架与django-polymorphic相结合的Pythonic解决方案。 鉴于: 如果我想要django-rest- framework中所有GalleryItem的列表,它只会给我GalleryItem(父模型)的字段,因此是:id,gallery_item_field和polymorphic_ctype。那不是我想要的 我想要custom

  • 我用ImageField创建了一个简单的模型,我想用django-rest-framework+django-rest-swagger创建一个api视图,它是文档化的,并且能够上传文件。 以下是我得到的: 我阅读了django-rest-framework中的这部分文档: 我正在使用、和。

  • 问题内容: 问题在于在django中接收到POST请求。我确实喜欢这样。 但是我得到ukeys的值为。当我检查时,我得到的值是 因此,如何在Django中将这些值作为列表获取? 谢谢! 问题答案: 后缀为jQueryPOST的数组,因为PHP和某些Web框架了解该约定,并自动为您在服务器端重新构建数组。Django不能那样工作,但是您应该能够通过以下方式访问数据:

  • Django带有聚合feed生成框架。有了它,你可以创建RSS或Atom只需继承django.contrib.syndication.views.Feed类。 让我们创建一个订阅源的应用程序。 在feed类, title, link 和 description 属性对应标准RSS 的<title>, <link> 和 <description>元素。 条目方法返回应该进入feed的item的元素。