Render template parts with extended cache control.

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
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 5, 2023
An ORM cache for Django.

Django ORMCache A cache manager mixin that provides some caching of objects for the ORM. Installation / Setup / Usage TODO Testing Run the tests with:

Educreations, Inc 15 Nov 27, 2022
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
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 7, 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 9, 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

null 92 Dec 13, 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
Django package to log request values such as device, IP address, user CPU time, system CPU time, No of queries, SQL time, no of cache calls, missing, setting data cache calls for a particular URL with a basic UI.

django-web-profiler's documentation: Introduction: django-web-profiler is a django profiling tool which logs, stores debug toolbar statistics and also

MicroPyramid 77 Oct 29, 2022
Jira-cache - Jira cache with python

Direct queries to Jira have two issues: they are sloooooow many queries are impo

John Scott 6 Oct 8, 2022
PaddleRobotics is an open-source algorithm library for robots based on Paddle, including open-source parts such as human-robot interaction, complex motion control, environment perception, SLAM positioning, and navigation.

简体中文 | English PaddleRobotics paddleRobotics是基于paddle的机器人开源算法库集,包括人机交互、复杂运动控制、环境感知、slam定位导航等开源算法部分。 人机交互 主动多模交互技术TFVT-HRI 主动多模交互技术是通过视觉、语音、触摸传感器等输入机器人

null 185 Dec 26, 2022
A Python command-line utility for validating that the outputs of a given Declarative Form Azure Portal UI JSON template map to the input parameters of a given ARM Deployment Template JSON template

A Python command-line utility for validating that the outputs of a given Declarative Form Azure Portal UI JSON template map to the input parameters of a given ARM Deployment Template JSON template

Glenn Musa 1 Feb 3, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 5, 2023
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Dec 31, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 7, 2023
Code for "Neural Parts: Learning Expressive 3D Shape Abstractions with Invertible Neural Networks", CVPR 2021

Neural Parts: Learning Expressive 3D Shape Abstractions with Invertible Neural Networks This repository contains the code that accompanies our CVPR 20

Despoina Paschalidou 161 Dec 20, 2022
Parametric open source reconstructions of Voron printed parts

The Parametric Voron This repository contains Fusion 360 reconstructions of various printed parts from the Voron printers

Matthew Lloyd 26 Dec 19, 2022
Codename generator using WordNet parts of speech database

codenames Codename generator using WordNet parts of speech database References: https://possiblywrong.wordpress.com/2021/09/13/code-name-generator/ ht

possiblywrong 27 Oct 30, 2022
This Project is based on NLTK It generates a RANDOM WORD from a predefined list of words, From that random word it read out the word, its meaning with parts of speech , its antonyms, its synonyms

This Project is based on NLTK(Natural Language Toolkit) It generates a RANDOM WORD from a predefined list of words, From that random word it read out the word, its meaning with parts of speech , its antonyms, its synonyms

SaiVenkatDhulipudi 2 Nov 17, 2021
This repository contains modules that extend / modify parts of Odoo ERP

Odoo Custom Addons This repository contains addons that extend / modify parts of Odoo ERP. Addons list account_cancel_permission Only shows the button

Daniel Luque 3 Dec 28, 2022
A program that automates the boring parts of completing the Daily accounting spreadsheet at Taos Ski Valley

TSV_Daily_App A program that automates the boring parts of completing the Daily accounting spreadsheet at my old job. To see how it works you will nee

Devin Beck 2 Jan 1, 2022