Skip to content

Decorator to add routes to a resource #101

@simonluijk

Description

@simonluijk

I use this on almost every project I use restless with. It would be great if you could add it to the project.

from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt


def routes(*configs):
    """
    A class decorator that adds extra routes to the resource.

    Usage:

        @routes(('POST', r'url_pattern/$', 'new_method1'),
                (('GET', 'POST'), r'url_pattern/$', 'new_method2'))
        class MyResource(Resource):
            def new_method1(self):
                pass
            def new_method2(self):
                pass
    """

    def decorator(cls):
        old_init = getattr(cls, '__init__')
        def __init__(self, *args, **kwargs):
            old_init(self, *args, **kwargs)
            for methods, path_regex, target in configs:
                if isinstance(methods, basestring):
                    methods = (methods, )
                conf = {}
                for method in methods:
                    conf[method] = target
                self.http_methods[target] = conf
        cls.__init__ = __init__

        old_urls = getattr(cls, 'urls')
        @classmethod
        def urls(cls, name_prefix=None):
            urls = old_urls(name_prefix=name_prefix)
            for method, path_regex, target in configs:
                name = cls.build_url_name(target, name_prefix)
                view = csrf_exempt(cls.as_view(target))
                urls.insert(0, url(path_regex, view, name=name))
            return urls
        cls.urls = urls

        return cls

    return decorator

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions