Created
June 13, 2013 07:15
-
-
Save copitux/5771788 to your computer and use it in GitHub Desktop.
App router to Django Rest Framework 2.3.5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.exceptions import ImproperlyConfigured | |
from django.db.models import get_app | |
from django.utils.importlib import import_module | |
from rest_framework.routers import DefaultRouter | |
from rest_framework.urlpatterns import format_suffix_patterns | |
class App(DefaultRouter): | |
""" | |
Extends ``DefaultRouter`` to work with django apps in order to decouple | |
``urls`` modules | |
It register the ``routers`` tuples in <app>.urls module, and also prepend | |
extra urls defined in ``router_patterns`` | |
** Example ** | |
test_app.urls :: | |
routers = ( | |
(r'url_prefix', ViewSet), | |
(r'other_prefix', OtherViewSet, 'with_base_name') | |
) | |
router_patterns = patterns('', | |
url(...) | |
) | |
project.urls :: | |
router = App() | |
router.register_app('test_app') | |
urlpatters = patterns('', | |
(r'^main-prefix/', router.urls) | |
) | |
instead of project.urls :: | |
router = DefaultRouter() | |
router.register(r'url_prefix', test_app.views.ViewSet) | |
router.register(r'other_prefix', test_app.views.OtherViewSet, | |
'with_base_name') | |
urlpatterns = patterns('', | |
(r'^main-prefix/', test_app.urls.router_patterns), | |
(r'^main-prefix/', router.urls) | |
) | |
""" | |
def __init__(self, *args, **kwargs): | |
super(App, self).__init__(*args, **kwargs) | |
self.extra_urls = [] | |
def register_app(self, app_name): | |
get_app(app_name) # Assert | |
app_urls_module = import_module("%s.urls" % app_name) | |
try: | |
routers = getattr(app_urls_module, 'routers') | |
router_patterns = getattr(app_urls_module, 'router_patterns', | |
False) | |
if router_patterns: | |
self.extra_urls += router_patterns | |
for router in routers: | |
super(App, self).register(*router) | |
except AttributeError: | |
raise ImproperlyConfigured("You should define ``routers`` tuple " | |
"in '%s'.urls module" % app_name) | |
def get_urls(self): | |
default_urls = super(App, self).get_urls() | |
extra_urls = self.extra_urls | |
if self.include_format_suffixes: | |
extra_urls = format_suffix_patterns(extra_urls) | |
return extra_urls + default_urls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment