-
Notifications
You must be signed in to change notification settings - Fork 4
/
decorators.py
37 lines (29 loc) · 1.18 KB
/
decorators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os
import inspect
from functools import wraps
from django.template.response import TemplateResponse
from django.utils.decorators import available_attrs
from django.views.generic.base import View
def restful_template(dirname, name, func=None):
def decorator(action):
# maintain correct stacktrace name and doc
@wraps(action, assigned=available_attrs(action))
def _restful(obj, request, *args, **kwargs):
template = os.path.join(dirname, name)
data = action(obj, request, *args, **kwargs)
if not (isinstance(data, tuple) or isinstance(data, dict) or data is None):
return data
status = 200
if isinstance(data, tuple):
status = data[1]
data = data[0]
return TemplateResponse(request, template, data, status=status)
return _restful
if func:
return decorator(func)
return decorator
def restful_view_templates(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
if name in View.http_method_names:
setattr(cls, name, restful_template(cls.__name__[:-4].lower(), name, func=m))
return cls