Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decorator to add routes to a resource #101

Open
simonluijk opened this issue May 29, 2017 · 1 comment
Open

Decorator to add routes to a resource #101

simonluijk opened this issue May 29, 2017 · 1 comment

Comments

@simonluijk
Copy link

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
@badeendjuh
Copy link

Leaving a note here for those wondering if this code is responsible for leaving random 501 not implemented errors on your app. This is not the case and look at #103 instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants