Render template parts with extended cache control.

Related tags

Cachingdjango-viewlet
Overview

Render template parts with extended cache control.

https://travis-ci.org/5monkeys/django-viewlet.svg?branch=master https://coveralls.io/repos/5monkeys/django-viewlet/badge.svg?branch=master

Installation

Install django-viewlet in your python environment

$ pip install django-viewlet

Supports Django versions 1.3 - 2.0 and Python versions 2.6 - 3.6.

Configuration

Add viewlet to your INSTALLED_APPS setting so Django can find the template tag

INSTALLED_APPS = (
    ...
    'viewlet',
)

Jinja2

If you're using Jinja2 as your template engine for Django versions < 1.8, put this in your Django settings:

VIEWLET_TEMPLATE_ENGINE = 'jinja2'

If you're using Coffin or Jingo, add the ViewletExtension to their settings, and optionally switch to their respective environment.

Coffin:

JINJA2_EXTENSIONS = (
    ...
    'viewlet.loaders.jinja2_loader.ViewletExtension',
)

VIEWLET_JINJA2_ENVIRONMENT = 'coffin.common.env'

Jingo:

JINJA_CONFIG = {
    'extensions': (
        ...
       'viewlet.loaders.jinja2_loader.ViewletExtension',
    ),
}

VIEWLET_JINJA2_ENVIRONMENT = 'jingo.get_env'

Django 1.8+:

Add ViewletExtension to the list of extensions of Jinja2 template engine

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        # ...
        'OPTIONS': {
            # ...
            'extensions': [
                # ...
                'viewlet.loaders.jinja2_loader.ViewletExtension',
            ],
        }
    }
],

Usage

A viewlet is almost like a function based django view, taking a template context as first argument instead of request. Place your viewlets in viewlets.py or existing views.py in your django app directory.

from django.template.loader import render_to_string
from viewlet import viewlet

@viewlet
def hello_user(context, name):
    return render_to_string('hello_user.html', {'name': name})

You can then render the viewlet with the viewlet template tag:

{% load viewlets %}
<p>{% viewlet hello_user request.user.username %}p>

... and in your Jinja2 templates:

<p>{% viewlet 'host_sponsors', host.id) %}p>

Specifying cache backend

By default viewlet will try using viewlet cache alias, falling back to default. You can specify which alias should be used in settings:

VIEWLET_DEFAULT_CACHE_ALIAS = 'template_cache'

CACHES = {
    # ...
    'template_cache': {
        # ...
    },
    # ...
}

Additionally, you can override cache alias in viewlet decorator with using argument

@viewlet(using='super_cache')
def hello_user(context, name):
    return render_to_string('hello_user.html', {'name': name})

Refreshing viewlets

A cached viewlet can be re-rendered and updated behind the scenes with viewlet.refresh

import viewlet
viewlet.refresh('hello_user', 'monkey')
# or
hello_user.refresh('monkey')

The decorator

@viewlet(name, template, key, timeout)
  • name
    Optional reference name for the viewlet, defaults to function name.
  • template
    Optional path to template. If specified the viewlet must return a context dict, otherwise it is responsible to return the rendered output itself.
  • key
    Optional cache key, if not specified a dynamic key will be generated viewlet:name(args...)
  • timeout
    Cache timeout. Defaults to configured cache backend default timeout, None = eternal, 0 = uncached.

Examples

The content returned by the viewlet will by default be cached. Use the timeout argument to change this.

@viewlet(timeout=30*60)
def hello_user(context, name):
    return render_to_string('hello_user.html', {'name': name})
Tip: Set timeout to None to cache forever and use viewlet.refresh to update the cache.

Django viewlet will by default build a cache key viewlet:name(args...). To customize this key pass a string to the viewlet decorator argument key that includes string mod operators for each viewlet argument.

@viewlet(timeout=30*60, key='some_cache_key_%s')
def hello_user(context, name):
    return render_to_string('hello_user.html', {'name': name})

Django viewlet will cache returned context instead of html by using the template decorator argument. This is useful if cached html is too heavy, or your viewlet template needs to be rendered on every call. The specified template will then be rendered with the viewlet context merged with the parent context, usually a RequestContext.

@viewlet(template='hello_user.html', timeout=30*60)
def hello_user(context, name):
    return {'name': name}
Note: Return context dict for the template, not rendered html/text

If there is no need for caching, set the viewlet decorator argument timeout to 0.

@viewlet(timeout=0)
def hello_user(context, name):
    return render_to_string('hello_user.html', {'name': name})

By default your viewlets will be named as the function. To override this you can set the decorator argument name

@viewlet(name='greeting')
def hello_user(context, name):
    return render_to_string('hello_user.html', {'name': name})

A powerful usage of viewlet.refresh is to use it together with Django signals:

class Product(Model):
    name = CharField(max_length=255)

@viewlet(timeout=None)
def product_teaser(context, id):
    product = get_context_object(Product, id, context)
    return render_to_string('product_teaser.html', locals())

def refresh_product_teaser(instance, **kwargs):
    viewlet.refresh('product_teaser', instance.id)

post_save.connect(refresh_product_teaser, Product)

Viewlets can also be accesses with AJAX by adding viewlet.urls to your Django root urls:

urlpatterns = patterns('',
    (r'^viewlet/', include('viewlet.urls')),
)

The url ends with the viewlet name followed by a querystring used as kwargs to the viewlet:

http://localhost:8000/viewlet/[name]/?arg=1...
Comments
  • Support for Django 1.9

    Support for Django 1.9

    This will add support for Django 1.9. The basis is incorporating these three open pull requests:

    https://github.com/5monkeys/django-viewlet/pull/33 https://github.com/5monkeys/django-viewlet/pull/34 https://github.com/5monkeys/django-viewlet/pull/35

    With some minor changes, and added build jobs.

    opened by alimony 2
  • Use sha1 digest instead of args in cache key

    Use sha1 digest instead of args in cache key

    It also fixes inability to set custom key after recent updates.

    One could also use cache backend with special KEY_FUNCTION but this way gives more control, so it may still have sense to merge it.

    ready for review 
    opened by andreif 2
  • Load jinja Environment lazily and cache it

    Load jinja Environment lazily and cache it

    This avoids a circular dependency when a project's jinja Environment is declared at the module level and depends on django settings (since django-viewlet imports the Environment at project startup).

    I have a project where I don't use either jingo or coffin, but instead I've rolled my own jinja2 integration. In this project I declare my jinja Environment at the module level like this:

    env = Environment(
        loader=FileSystemLoader(settings.JINJA_TEMPLATE_DIRS),
        extensions=settings.JINJA_EXTENSIONS,
        autoescape=True,
    )
    

    This doesn't work with the current version of viewlet, but this pull request fixes it.

    I made these changes pretty fast without too much insight in the code base, so please look them through if you're going to merge them :). All tests passes at least.

    opened by heyman 1
  • Fixing the refresh bug

    Fixing the refresh bug

    To resolve the problems with the refresh functionality I moved the core responsibility of Viewlet.call() to a new method: _call()

    call() now only handles the rendering of context viewlets and let's _call() do the rest to allow refresh to use _call() instead to avoid unnecessary rendering while updating the cache.

    fixes #23

    opened by gardeman 0
  • Refreshing context viewlets using jinja templates and extra context breaks

    Refreshing context viewlets using jinja templates and extra context breaks

    When calling viewlet.refresh() on a context viewlet; that triggers the whole rendering process, which causes rendering of jinja2-templates to raise if the template expects extra context variables not given by the viewlet itself.

    To fix this the refresh function no longer may return the actual rendered viewlet. Is this a problem API wise?

    bug question 
    opened by gardeman 0
  • Error in readme regarding VIEWLET_JINJA2_ENVIRONMENT

    Error in readme regarding VIEWLET_JINJA2_ENVIRONMENT

    When using jingo the env should be configured to:

    VIEWLET_JINJA2_ENVIRONMENT = 'jingo.env' NOT VIEWLET_JINJA2_ENVIRONMENT = 'jingo.get_env'

    otherwise all the jingo helpers won't be accessible from within the viewlet's templates

    opened by gardeman 0
Releases(1.4.0)
Owner
5 Monkeys
5 Monkeys
Asyncio cache manager for redis, memcached and memory

aiocache Asyncio cache supporting multiple backends (memory, redis and memcached). This library aims for simplicity over specialization. All caches co

aio-libs 764 Jan 02, 2023
Automatic caching and invalidation for Django models through the ORM.

Cache Machine Cache Machine provides automatic caching and invalidation for Django models through the ORM. For full docs, see https://cache-machine.re

846 Nov 26, 2022
Persistent caching for python functions

Cashier Persistent caching for python functions Simply add a decorator to a python function and cache the results for future use. Extremely handy when

Anoop Thomas Mathew 82 Mar 04, 2022
Render template parts with extended cache control.

Render template parts with extended cache control. Installation Install django-viewlet in your python environment $ pip install django-viewlet Support

5 Monkeys 59 Apr 05, 2022
WSGI middleware for sessions and caching

Cache and Session Library About Beaker is a web session and general caching library that includes WSGI middleware for use in web applications. As a ge

Ben Bangert 500 Dec 29, 2022
johnny cache django caching framework

Johnny Cache is a caching framework for django applications. It works with the django caching abstraction, but was developed specifically with the use

Jason Moiron 304 Nov 07, 2022
A slick ORM cache with automatic granular event-driven invalidation.

Cacheops A slick app that supports automatic or manual queryset caching and automatic granular event-driven invalidation. It uses redis as backend for

Alexander Schepanovski 1.7k Dec 30, 2022
Persistent, stale-free, local and cross-machine caching for Python functions.

Persistent, stale-free, local and cross-machine caching for Python functions.

Shay Palachy 420 Dec 22, 2022
An implementation of memoization technique for Django

django-memoize django-memoize is an implementation of memoization technique for Django. You can think of it as a cache for function or method results.

Unhaggle 118 Dec 09, 2022
Robust, highly tunable and easy-to-integrate in-memory cache solution written in pure Python, with no dependencies.

Omoide Cache Caching doesn't need to be hard anymore. With just a few lines of code Omoide Cache will instantly bring your Python services to the next

Leo Ertuna 2 Aug 14, 2022
Aircache is an open-source caching and security solution that can be integrated with most decoupled apps that use REST APIs for communicating.

AirCache Aircache is an open-source caching and security solution that can be integrated with most decoupled apps that use REST APIs for communicating

AirCache 2 Dec 22, 2021
Asynchronous cache manager designed for horizontally scaled web servers.

Introduction Asynchronous cache manager designed for horizontally scaled web applications. NOTE: Currently has implementation only for FastAPI using R

Serghei 23 Dec 01, 2022
Extensible memoizing collections and decorators

cachetools This module provides various memoizing collections and decorators, including variants of the Python Standard Library's @lru_cache function

Thomas Kemmer 1.5k Jan 05, 2023
A Redis cache backend for django

Redis Django Cache Backend A Redis cache backend for Django Docs can be found at http://django-redis-cache.readthedocs.org/en/latest/. Changelog 3.0.0

Sean Bleier 1k Dec 15, 2022
RecRoom Library Cache Tool

RecRoom Library Cache Tool A handy tool to deal with the Library cache file. Features Parse Library cache Remove Library cache Parsing The script pars

Jesse 5 Jul 09, 2022
A caching extension for Flask

A fork of the Flask-cache extension which adds easy cache support to Flask.

Pallets Community 773 Jan 08, 2023
No effort, no worry, maximum performance.

Django Cachalot Caches your Django ORM queries and automatically invalidates them. Documentation: http://django-cachalot.readthedocs.io Table of Conte

NoriPyt 976 Dec 28, 2022
Automatic Flask cache configuration on Heroku.

flask-heroku-cacheify Automatic Flask cache configuration on Heroku. Purpose Configuring your cache on Heroku can be a time sink. There are lots of di

Randall Degges 39 Jun 05, 2022
Peerix is a peer-to-peer binary cache for nix derivations

Peerix Peerix is a peer-to-peer binary cache for nix derivations. Every participating node can pull derivations from each other instances' respective

92 Dec 13, 2022
A decorator for caching properties in classes.

cached-property A decorator for caching properties in classes. Why? Makes caching of time or computational expensive properties quick and easy. Becaus

Daniel Roy Greenfeld 658 Dec 01, 2022