On Apr 11, 2010, at 5:58 AM, ydjango wrote:
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

I use classes that derive from HttpResponse. Something like:


class View(HttpResponse):
    def content(self):
        template = loader.get_template(self.template_file)
        context  = RequestContext(
                self.request,
                self.context_dict(),
                processors=self.processors)
        return template.render(context)

    # ... more of such


class MyView(View):
    template_file = 'my_template.html'
    processors    = (my_processor,)

    def __init__(self, request, *args, **kwargs):
        self.request, self.args, self.kwargs = request, args, kwargs
        super(MyView, self).__init__(self, self.content())

    def context_dict(self):
        return dict(
                var1 = 'var1',
                var2 = 'var2',
                )

    # ... and so on


I will probably post a more extensive code snippet to django-dev and django-snippets in a few weeks.

Kind regards,

Roald

--
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.

Reply via email to