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
PyCache - simple key:value server written with Python

PyCache simple key:value server written with Python and client is here run server python -m pycache.server or from pycache.server import start_server

chick_0 0 Nov 01, 2022
Python disk-backed cache (Django-compatible). Faster than Redis and Memcached. Pure-Python.

DiskCache is an Apache2 licensed disk and file backed cache library, written in pure-Python, and compatible with Django.

Grant Jenks 1.7k Jan 05, 2023
A caching extension for Flask

Flask-Caching Adds easy cache support to Flask. This is a fork of the Flask-Cache extension. Flask-Caching also includes the cache module from werkzeu

Peter Justin 774 Jan 02, 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
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
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
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
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
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
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
A Python wrapper around the libmemcached interface from TangentOrg.

pylibmc is a Python client for memcached written in C. See the documentation at sendapatch.se/projects/pylibmc/ for more information. New in version 1

Ludvig Ericson 458 Dec 30, 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
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
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
Simple caching transport for httpx

httpx-cache is yet another implementation/port is a port of the caching algorithms in httplib2 for use with httpx Transport object.

Ouail 28 Jan 01, 2023
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
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
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
Caching for HTTPX

Caching for HTTPX. Note: Early development / alpha, use at your own risk. This package adds caching functionality to HTTPX Adapted from Eric Larson's

Johannes 51 Dec 04, 2022