Nips
Nips

Reputation: 13880

Dynamic templatetag

I have my own templatetag:

@register.inclusion_tag('path_to_module.html', takes_context=True)
def getmodule(context, token):
    try:
        return slow_function(params)
    except Exception, e:
        return None

And it is very slow. Template waiting for this tags.

Can I call them asynchonously?

Upvotes: 2

Views: 98

Answers (2)

Tom
Tom

Reputation: 5835

If it's cacheable (doesn't need to be unique per page view); then cache it. Either using Django's cache API in your templatetag, or template fragment caching directly in your template. As @jpic says, if it's something that takes a while to recalculate - pass it off to a task queue like Celery.

If you need this function to run every page view for whatever reason; then separate it out in to a new view and load it in to some container in your main template asynchronously using JavaScript.

Upvotes: 2

jpic
jpic

Reputation: 33420

You can execute python functions in a background process:

You could create a background task that renders path_to_module and caches the output. When the cache should be invalidated: run slow_function in the background again.

Upvotes: 0

Related Questions