caching.py 1.62 KB
Newer Older
1 2 3 4 5 6
"""
Helper functions for caching course assets.
"""
from django.core.cache import caches
from django.core.cache.backends.base import InvalidCacheBackendError
from opaque_keys import InvalidKeyError
7
from xmodule.contentstore.content import STATIC_CONTENT_VERSION
8 9 10 11 12 13 14 15 16 17 18 19 20

# See if there's a "course_assets" cache configured, and if not, fallback to the default cache.
CONTENT_CACHE = caches['default']
try:
    CONTENT_CACHE = caches['course_assets']
except InvalidCacheBackendError:
    pass


def set_cached_content(content):
    """
    Stores the given piece of content in the cache, using its location as the key.
    """
21
    CONTENT_CACHE.set(unicode(content.location).encode("utf-8"), content, version=STATIC_CONTENT_VERSION)
22 23 24 25 26 27


def get_cached_content(location):
    """
    Retrieves the given piece of content by its location if cached.
    """
28
    return CONTENT_CACHE.get(unicode(location).encode("utf-8"), version=STATIC_CONTENT_VERSION)
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48


def del_cached_content(location):
    """
    Delete content for the given location, as well versions of the content without a run.

    It's possible that the content could have been cached without knowing the course_key,
    and so without having the run.
    """
    def location_str(loc):
        """Force the location to a Unicode string."""
        return unicode(loc).encode("utf-8")

    locations = [location_str(location)]
    try:
        locations.append(location_str(location.replace(run=None)))
    except InvalidKeyError:
        # although deprecated keys allowed run=None, new keys don't if there is no version.
        pass

49
    CONTENT_CACHE.delete_many(locations, version=STATIC_CONTENT_VERSION)