Skip to content

Instantly share code, notes, and snippets.

@sorl
Last active October 3, 2015 18:25
Show Gist options
  • Save sorl/4d82c7d5add983704a90 to your computer and use it in GitHub Desktop.
Save sorl/4d82c7d5add983704a90 to your computer and use it in GitHub Desktop.
Django CBV
import re
from django.http import HttpResponse
from django.shortcuts import render
from functools import wraps
uncamel_patterns = (
re.compile('(.)([A-Z][a-z]+)'),
re.compile('([a-z0-9])([A-Z])'),
)
def uncamel(s):
"""
Make camelcase lowercase and use underscores.
>>> uncamel('CamelCase')
'camel_case'
>>> uncamel('CamelCamelCase')
'camel_camel_case'
>>> uncamel('Camel2Camel2Case')
'camel2_camel2_case'
>>> uncamel('getHTTPResponseCode')
'get_http_response_code'
>>> uncamel('get2HTTPResponseCode')
'get2_http_response_code'
>>> uncamel('HTTPResponseCode')
'http_response_code'
>>> uncamel('HTTPResponseCodeXYZ')
'http_response_code_xyz'
"""
for pat in uncamel_patterns:
s = pat.sub(r'\1_\2', s)
return s.lower()
class Context(object):
pass
def view(cls):
"""
View decorator must wrap view class
"""
@wraps(cls)
def wrapper(request, **kwargs):
obj = cls(request, **kwargs)
handler = getattr(obj, request.method.lower(), None)
if handler is None:
return HttpResponse(status_code=405)
return handler(obj.c) or obj.render(obj.c)
return wrapper
class View(object):
def __init__(self, request, **kwargs):
self.c = Context()
self.r = request
self.u = request.user
self.c.user = self.u
for k, v in kwargs.items():
setattr(self, k, v)
self.setup(self.c)
def setup(self, c):
pass
def render(self, c):
app = self.__module__.split('.')[0]
template = '%s/%s.html' % (app, uncamel(self.__class__.__name__))
return render(self.r, template, c.__dict__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment