On 04/12/2010 12:03 PM, zweb wrote:
To Summarize, two options are,
1) Template method pattern which Thierry suggested
http://en.wikipedia.org/wiki/Template_method_pattern
2) Django Decorators
(there is a third way with middleware)
1) Writing a custom decorator is the easiest way to get refactoring
benefits. There are some tricks with decorators (using a nested class
to bind variables) but these are well documented in normal python
documentation.
2) Rewriting your views as classes is the modular way and probably the
most flexible.
A nice trick with the use of inheritance is to make the class a callable
def __call__(self, request, **kwargs):
This method provides the view
Then you can instantiate the class and call it as if it were a method.
MyView=MyViewClass()
and MyView can be used in your urls.py as if it were a normal view.
3) If you want to perform an action before every page is served, you can
define middleware to do some processing. For instance you can make a
whole site password protected very easily and not need a @login_required
decorator. You just have to let the login and logout screens pass
through the middleware.
This works if you really want to do the same thing for EVERY page.
Carl
On Apr 10, 11:38 pm, Thierry Chich<thierry.ch...@gmail.com> wrote:
I have written my functions as méthods of classes. Then it allow to
use inheritance.
Le 11 avr. 2010 à 05:58, ydjango<neerash...@gmail.com> a écrit :
I find all my view method have identical code in start and in end:
anyway to avoid repetition...?
Example:
def typical_view_method(request):
Check if user is authenticated.
Get user and group
Get some session variables
try:
Method specific logic
except Exception, e:
view_logger.error('error in typical_view_method:%s', e)
response = HttpResponse(json_data, mimetype = 'application/json')
response.__setitem__('Cache-Control', 'no-store,no-cache')
response.__setitem__('Pragma', 'no-cache')
response.__setitem__('Expires', '-1')
return response
--
You received this message because you are subscribed to the Google
Groups "Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com
.
For more options, visit this group
athttp://groups.google.com/group/django-users?hl=en
.
--
Carl Zmola
301-562-1900 x315
czm...@woti.com
--
You received this message because you are subscribed to the Google Groups "Django
users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.