Hello,

This is not a secret that I'm interested in both Django and Semantic  
Web. I'm following discussion about Django+REST for more than two  
years and when I realize that newforms-admin branch will use class- 
based generic views [1], I decided that it's probably the right moment  
to do something with that.

[1] http://code.djangoproject.com/ticket/6735

The attached code is built on top of this patch, I need to discuss  
with jkocherhans in order to avoid duplicate code but consider it more  
as a proof-of-concept for now, here is the (incomplete) doc:


     ModelView: a RESTful class-based view of your resources
     =======================================================

     Philosophy
     ----------

     The goal of this class is to provide a lightweight REST  
interface, I know
     that django-rest-interface exists but it's abandoned and it  
suffers from
     some defaults. Given my experience with it, I always need to  
rewrite large
     parts of the library in order to customize it to fits with my own  
needs.

     In order to avoid this with ModelView, the philosophy is to allow
     dead-easy subclassing with granularity at each point.

     Note: I totally respect what had been done before and this class is
     inspired from a lot of existing projects so many thanks to all  
authors.


     Goals
     -----

     Basically, it dispatches requests to the appropriated function  
given the
     HTTP verb and it allows you to specify a responder in order to  
avoid
     duplication of code at the resource logic level.

     You can specify your own responders, and restrict to allowed HTTP  
methods.

     Secret goal: to be honest, I dream of resource oriented stuff in
     Django's trunk for years now. A RESTful Django's (newforms-)admin  
could be
     awesome too in order to provide a built-in API!


     Example
     -------

     A quick example in order to demonstrate what is possible.

     models.py::

         class Post(models.Model):
             title = models.Charfield(max_length=200)
             slug = models.SlugField(max_length=200,  
prepopulate_from=('title',), unique=True)
             content = models.TextField()

     urls.py::

         blog = ModelView(Post.objects.filter(is_online=True),  
responders=(HtmlResponder, JsonResponder), methods=('GET',))
         blog_admin = ModelView(Post.objects.all(), methods=('GET',  
'POST', 'PUT', 'DELETE'))
         urlpatterns = pattern('',
             url(^blog/(?P<slug>[-\w]+)/(?P<format>(html|json))?/?$),  
blog, name='blog'),
             url(^blog/admin/(?P<object_pk>\d)/), blog_admin,  
name='blog_admin'),
         )

     Note: here we consider that you want a custom admin for your blog,
     otherwise Django's built-in admin is much more interesting, of  
course.


     TODO
     ----

         * Add tests and documentation
         * Create a collection of generic Responders
         * Handle receivers in order to use it as an API (for the  
moment,
           it assumes that you receive formencoded data), need more  
reflexion.
         * Handle privacy, need more reflexion
         * See what can be done with APP, it could be fun!
         * Ideas?


I know that it needs tests and documentation but I'd like to bring the  
discussion here because I think it's important to have feedback before  
going too deep. So let me know if my secret goals above are crazy or  
if I need to spend more time on this.

Cheers,
David (aka david`bgk on #django-dev)



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.http import Http404, HttpResponse, HttpResponseNotAllowed
from django.views.generic.base import BaseDetailView


class HtmlResponder(object):
    """
    HtmlResponder renders an object or a list of objects with the Django
    templating system.
    """
    def __init__(self, queryset):
        self.queryset = queryset
        
    def render_response(self, request, template, context_vars, mimetype=None):
        """
        Returns an HttpResponse for the given request, template object,
        dictionary of context variables, and optional mimetype.
        """
        context = RequestContext(request, context_vars)
        template = template.render(context)
        return HttpResponse(template, mimetype=mimetype)
    
    def get_template(self, opts, target='list'):
        """
        Returns a loaded template, the template_name depends of the model name.
        
        Examples::
        
            blog/post_list.html
            auth/user_detail.html
        """
        template_name = "%s/%s_%s.html" % (opts.app_label, opts.object_name.lower(), target)
        return loader.get_template(template_name)
    
    def get_context_vars(self, context_vars):
        """
        Returns a dictionary of context vars, override if you need more.
        """
        return context_vars
    
    def list(self, request, paginate_by, allow_empty):
        """
        Renders a list of model objects to HttpResponse.
        """
        if paginate_by:
            paginator = QuerySetPaginator(self.queryset, paginate_by,
                                          allow_empty_first_page=allow_empty)
            page = request.GET.get('page', 1)
            try:
                page_number = int(page)
            except ValueError:
                if page == 'last':
                    page_number = paginator.num_pages
                else:
                    # Page is not 'last', nor can it be converted to an int.
                    raise Http404
            try:
                page_obj = paginator.page(page_number)
            except InvalidPage:
                raise Http404
            object_list = page_obj.object_list
        else:
            object_list = self.queryset
            paginator = None
            page_obj = None
            if not allow_empty and len(self.queryset) == 0:
                raise Http404
        context_vars = self.get_context_vars({
            'object_list': object_list,
            'paginator': paginator,
            'page_obj': page_obj
        })
        opts = self.queryset.model._meta
        template = self.get_template(opts)
        return self.render_response(request, template, context_vars)

    def element(self, request, obj):
        """
        Renders single model objects to HttpResponse.
        """
        context_vars = self.get_context_vars({'object': obj})
        opts = self.queryset.model._meta
        template = self.get_template(opts, target='detail')
        response = self.render_response(request, template, context_vars)
        populate_xheaders(request, response, self.queryset.model, getattr(obj, opts.pk.name))
        return response
    
    def create_success(self, request, new_obj, post_save_redirect):
        """
        Returns an HttpResonse, generally an HttpResponse redirect. This will
        be the final return value of the view and will only be called if the
        object was saved successfuly.
        """
        # Redirect to the new object: first by trying post_save_redirect,
        # then by obj.get_absolute_url; fail if neither works.
        if post_save_redirect:
            return HttpResponseRedirect(post_save_redirect % new_obj.__dict__)
        elif hasattr(new_obj, 'get_absolute_url'):
            return HttpResponseRedirect(new_obj.get_absolute_url())
        else:
            raise ImproperlyConfigured("No URL to redirect to from generic create view.")

    def update_success(self, request, obj, new_obj, post_save_redirect):
        """
        Returns an HttpResonse, generally an HttpResponse redirect. This will
        be the final return value of the view and will only be called if the
        object was saved successfuly.
        """
        # Redirect to the new object: first by trying post_save_redirect,
        # then by obj.get_absolute_url; fail if neither works.
        if post_save_redirect:
            return HttpResponseRedirect(post_save_redirect % new_obj.__dict__)
        elif hasattr(new_obj, 'get_absolute_url'):
            return HttpResponseRedirect(new_obj.get_absolute_url())
        else:
            raise ImproperlyConfigured("No URL to redirect to from generic create view.")

    def delete_success(self, post_save_redirect):
        return HttpResponseRedirect(post_save_redirect)
        

class JsonResponder(object):
    """TODO"""


class ModelView(BaseDetailView):
    """
    ModelView: a RESTful class-based view of your resources
    =======================================================
    
    Philosophy
    ----------
    
    The goal of this class is to provide a lightweight REST interface, I know
    that django-rest-interface exists but it's abandoned and it suffers from
    some defaults. Given my experience with it, I always need to rewrite large
    parts of the library in order to customize it to fits with my own needs.
    
    In order to avoid this with ModelView, the philosophy is to allow 
    dead-easy subclassing with granularity at each point.
    
    Note: I totally respect what had been done before and this class is 
    inspired from a lot of existing projects so many thanks to all authors.
    
    
    Goals
    -----
    
    Basically, it dispatches requests to the appropriated function given the
    HTTP verb and it allows you to specify a responder in order to avoid 
    duplication of code at the resource logic level.
    
    You can specify your own responders, and restrict to allowed HTTP methods.
    
    Secret goal: to be honest, I dreamt of resource oriented stuff in 
    Django's trunk for years now. A RESTful Django's (newforms-)admin could be
    awesome too in order to provide a built-in API!
        
    
    Example
    -------
    
    A quick example in order to demonstrate what is possible.
    
    models.py::
    
        class Post(models.Model):
            title = models.Charfield(max_length=200)
            slug = models.SlugField(max_length=200, prepopulate_from=('title',), unique=True)
            content = models.TextField()
        
    urls.py::
    
        blog = ModelView(Post.objects.filter(is_online=True), responders=(HtmlResponder, JsonResponder), methods=('GET',))
        blog_admin = ModelView(Post.objects.all(), methods=('GET', 'POST', 'PUT', 'DELETE'))
        urlpatterns = pattern('', 
            url(^blog/(?P<slug>[-\w]+)/(?P<format>(html|json))?/?$), blog, name='blog'),
            url(^blog/admin/(?P<object_pk>\d)/), blog_admin, name='blog_admin'),
        )
    
    Note: here we consider that you want a custom admin for your blog,
    otherwise Django's built-in admin is much more interesting, of course.
    
    
    TODO
    ----
    
        * Add tests and documentation
        * Create a collection of generic Responders
        * Handle receivers in order to use it as an API (for the moment,
          it assumes that you receive formencoded data), need more reflexion.
        * Handle privacy, need more reflexion
        * See what can be done with APP, it could be fun!
        * Ideas?
    
    """
    def __init__(self, queryset, slug_field='slug', post_save_redirect=None,
            paginate_by=None, allow_empty=True,
            responders=(HtmlResponder,), methods=('GET', 'POST', 'PUT', 'DELETE')):
        self.post_save_redirect = post_save_redirect
        self.paginate_by = paginate_by
        self.allow_empty = allow_empty
        self.responders = dict((responder.__class__.__name__, responder) for responder in responders)
        self.methods = methods
        super(ModelView, self).__init__(queryset, slug_field)

    def __call__(self, request, object_pk=None, slug=None, format='html'):
        """
        Redirects to one of the CRUD methods depending on the HTTP method of 
        the request. Checks whether the requested method is allowed for this 
        resource.
        """
        # If we didn't get object_pk or slug, assume this is an add view.
        if object_pk is None and slug is None:
            obj = None
        else:
            obj = self.get_object(request, object_pk, slug)
        
        # Restrict
        request_method = request.method.upper()
        if request_method not in self.methods:
            raise HttpMethodNotAllowed
        
        # Dispatch
        if request_method == 'GET':
            return self.read(request, obj, self.get_responder(format))
        elif request_method == 'POST':
            return self.create(request, self.get_responder(format))
        elif request_method == 'PUT':
            return self.update(request, obj, self.get_responder(format))
        elif request_method == 'DELETE':
            return self.delete(request, obj, self.get_responder(format))
        else:
            raise Http404

    def get_responder(self, format):
        """
        Returns a ``Responder`` instance given the format.
        """
        try:
            return self.responders['%sResponder' % format.title()](self.get_query_set())
        except KeyError:
            raise ImproperlyConfigured("%s responder doesn't exist." % '%sResponder' % format.title())

    def get_form(self, request):
        """
        Returns a ``ModelForm`` class to be used in this view.
        """
        # TODO: we should be able to construct a ModelForm without creating
        # and passing in a temporary inner class
        class Meta:
            model = self.model
        class_name = self.model.__name__ + 'Form'
        return ModelFormMetaclass(class_name, (ModelForm,), {'Meta': Meta})

    def save_form(self, request, form):
        """
        Saves and returns the object represented by the given form. This
        method will only be called if the form is valid.
        """
        return form.save()

    def read(self, request, obj, responder):
        """
        Returns a rendered list or element whether ``obj`` exists, idempotent.
        """
        if obj is None:
            return responder.list(request, self.paginate_by, self.allow_empty)
        else:
            return responder.element(request, obj)

    def create(self, request, responder):
        """
        Create a new resource.
        """
        Form = self.get_form(request)
        form = Form(request.POST, request.FILES)
        if form.is_valid():
            new_obj = self.save_form(request, form)
            return responder.create_success(request, new_obj, self.post_save_redirect)

    def update(self, request, obj, responder):
        """
        Update an existing resource (there is no PUT creation for now), idempotent.
        """
        Form = self.get_form(request)
        form = Form(request.POST, request.FILES, instance=obj)
        if form.is_valid():
            new_obj = self.save_form(request, form)
            return responder.update_success(request, obj, new_obj, self.post_save_redirect)

    def delete(self, request, obj, responder):
        """
        Delete an existing resource, idempotent.
        """
        if obj is not None:
            obj.delete()
        return responder.delete_success(self.post_save_redirect)



Reply via email to