Last active
December 21, 2015 23:49
-
-
Save brehaut/6384870 to your computer and use it in GitHub Desktop.
simple views and contexts for django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from render import render | |
def some_context(request): | |
return {…} | |
def some_different_context(request): | |
return {…} | |
@render("template.html") | |
def viewname(request): | |
return [ | |
some_context(request), | |
some_different_context(request) | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Mapping | |
from functools import reduce | |
from django.shortcuts import render_to_response | |
from django.http import HttpResponse | |
from django.template import RequestContext | |
def merge(dicts): | |
"""Merge an iterable of dictionaries into one dictionary | |
If python was actually cool: | |
def merge(dicts): | |
return reduce((lambda acc, d: acc.update(d) or acc), dicts, {}) | |
""" | |
d = {} | |
for d_ in dicts: | |
d.update(d_) | |
return d | |
def render(template): | |
"""render is a variant on django-annoying's view decorating function. | |
render knows about template context dictionaries, and iterables of dictionaries | |
(that are merged with merge above). | |
the template name is passed to render. If a view returns an django HTTP | |
response object then that is returned in its place. | |
""" | |
def decorator(view): | |
def wrapper(request, *args, **kwargs): | |
res = view(request, *args, **kwargs) | |
if isinstance(res, HttpResponse): | |
return res | |
elif not isinstance(res, Mapping): | |
context = merge(res) | |
else: | |
context = res | |
return render_to_response(template, context, RequestContext(request)) | |
return wrapper | |
return decorator | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment