1. Kevin Veroneau
  2. django-odb


django-odb / odb / middleware.py

from django.http import HttpResponse
from django.forms.forms import Form
from django.views.generic.edit import FormView
from odb.traverse import get_object
from inspect import isclass
from django.template.base import Template
from django.template.context import RequestContext
from django.shortcuts import render

class TraversalMiddleware(object):
    def process_request(self, req):
            o = get_object(req.path)
            if hasattr(o, '__getitem__') and 'index' in o:
                o = o['index']
            if hasattr(o, 'render') and callable(o.render):
                return o.render(req)
            elif isinstance(o, HttpResponse):
                return o
            elif isinstance(o, str):
                return HttpResponse(o)
            elif isclass(o) and issubclass(o, Form):
                return FormView.as_view(form_class=o, template_name="odb/form.html")(req)
            elif isinstance(o, Template):
                return HttpResponse(o.render(RequestContext(req,{'GET':req.GET})))
            elif hasattr(o, 'keys') and callable(o.keys):
                if req.path[-1]!='/':
                    return None
                object_list = []
                for k, v in o.iteritems():
                    obj = {'name':k, 'class':v.__class__.__name__}
                    if isinstance(v, dict): obj.update({'is_directory':True})
                return render(req, "odb/object_list.html", {'object_list':object_list,'path':req.path})
            return None
        except KeyError:
            return None