Login

Snippets by panyam

Snippet List

Using class methods as views

This set of handlers allow one to isolate requests based on the method posted. Normally, in a view, we would do checks for request.method value and update the resource accordingly. This makes the view code pretty messy. So one way to avoid these check each time is to have a handler method (resource_handler above), that checks for the method parameter and dispatches to the handler withe the prefix <method>_handler_<suffix>. This also has the advantage of grouping related actions in a particular class. At the same time a new instance of the request handler is not created on each request (as with the google appengine handler?). Yet another advantage is by making the handler methods as class methods, the handler classes can be inherited to add further functionality to a resource "group. The disadvantage however is the inability to restrict access to a handler method to only particular methods. Eg above the "r'obja/(?P<id>[^\/]+)/delete/" would map to the delete_handler_objects if themethod was "delete" and post_handler_objects if the method was "post". However this can be worked with a different suffix passed to the handler_params method. Infact setting the suffix to "objects_delete" would result in a "delete_handler_objects_delete" handler on delete method and a Http404 on all others. Another inconvinience is the inability to detect a view handler by simply inspecting the url patterns. However, this information is carried within the handler_suffix and handler_class parameters which may infact provide greater insight into the semantics around the view handlers. Needless to say, this easily extends rest based accesses. Would greatly appreciate feedback and improvements.

  • django
  • views
  • class
  • methods
Read More

panyam has posted 1 snippet.