Skip to content

Instantly share code, notes, and snippets.

@thelonecabbage
Created October 2, 2013 14:40
Show Gist options
  • Save thelonecabbage/6794813 to your computer and use it in GitHub Desktop.
Save thelonecabbage/6794813 to your computer and use it in GitHub Desktop.
Using decorators to simplify declaring actions on Tastypie Resources
from utils.api import action, actionurls
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
class NoteResource(ModelResource):
class Meta:
object_class = Note
queryset = Note.objects.all()
authorization = Authorization()
def prepend_urls(self, *args, **kargs):
urls = actionurls(self)
return urls
@action()
def share(self, request, **kwargs):
return self.create_response(request, {
'success': True
})
@action(name='shareEmail')
def email(self, request, **kwargs):
return self.create_response(request, {
'success': True
})
from django.conf.urls import url
from tastypie.utils import trailing_slash
def actionurls(self):
urls = []
for name, method in self.__class__.__dict__.iteritems():
if hasattr(method, "is_auto_action"):
actionName = name if not hasattr(method, "auto_action_name") \
else method.auto_action_name
urls.append(
url(r"^(?P<resource_name>%s)/%s%s$" % (
self._meta.resource_name,
actionName,
trailing_slash()),
self.wrap_view(name), name="api_action_%s" % actionName)
)
return urls
def action(name=None):
def wrap(method):
method.is_auto_action = True
if not name is None:
method.auto_action_name = name
return method
return wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment