decorators.py 3.62 KB
# -*- coding: utf-8 -*-

from functools import wraps
from inspect import getargspec

from django.http import HttpResponse
from django.template.loader import render_to_string
from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.db import transaction

from common.util import json_decode, json_encode
from common.util import stringify_keys


class AjaxError(Exception):
    pass


def json_decode_fallback(value):
    try:
        return json_decode(value)
    except ValueError:
        return value


def ajax(login_required=True, method=None, encode_result=True, template=None,
         permission_required=None):
    def decorator(fun):
        @wraps(fun)
        def ajax_view(request):
            kwargs = {}
            request_params = None
            if method == 'post':
                request_params = request.POST
            elif method == 'get':
                request_params = request.GET
            fun_params, xx, fun_kwargs, defaults = getargspec(fun)
            if defaults:
                required_params = fun_params[1:-len(defaults)]
            else:
                required_params = fun_params[1:]
            missing_params = set(required_params) - set(request_params)
            if missing_params:
                res = {
                    'result': 'missing params',
                    'missing': ', '.join(missing_params),
                }
            else:
                if request_params:
                    request_params = dict(
                        (key, json_decode_fallback(value))
                        for key, value in request_params.iteritems()
                        if fun_kwargs or key in fun_params)
                    kwargs.update(stringify_keys(request_params))
                res = None
                if login_required and not request.user.is_authenticated():
                    res = {'result': 'logout'}
                if (permission_required and
                        not request.user.has_perm(permission_required)):
                    res = {'result': 'access denied'}
            if not res:
                try:
                    res = fun(request, **kwargs)
                    if res and template:
                        res = {'html': render_to_string(
                            template, res, RequestContext(request))}
                except AjaxError as e:
                    transaction.rollback()
                    res = {'result': e.args[0]}
            if encode_result:
                if 'result' not in res:
                    res['result'] = 'ok'
                return HttpResponse(
                    json_encode(res), content_type='application/json')
            else:
                return res

        return ajax_view

    return decorator

# żeby były linki do szablonów w PyCharm przy ajaxach
render_ajax = ajax


def render(template=None, content_type=None):
    content_type = content_type or settings.DEFAULT_CONTENT_TYPE

    def decorator(func):
        template_name = template or func.__name__ + '.html'

        @wraps(func)
        def renderer(request, *args, **kw):
            output = func(request, *args, **kw)
            if isinstance(output, (list, tuple)):
                return render_to_response(
                    output[1], output[0], RequestContext(request),
                    content_type=content_type)
            elif isinstance(output, dict):
                return render_to_response(
                    template_name, output, RequestContext(request),
                    content_type=content_type)
            return output

        return renderer

    return decorator