Python django.conf.urls.include() Examples

The following are code examples for showing how to use django.conf.urls.include(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-subadmin   Author: inueni   File: __init__.py    MIT License 6 votes vote down vote up
def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        base_viewname = self.get_base_viewname()

        urlpatterns = [
            url(r'' , include(self.get_subadmin_urls())),
            url(r'^$', wrap(self.changelist_view), name='%s_changelist' % base_viewname),
            url(r'^add/$', wrap(self.add_view), name='%s_add' % base_viewname),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_history' % base_viewname),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_delete' % base_viewname),
            url(r'^(.+)/change/$', wrap(self.change_view), name='%s_change' % base_viewname),
        ]

        urlpatterns =  urlpatterns
        return urlpatterns 
Example 2
Project: django-popup-field   Author: yinkh   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def urls(cls):
        """
        generate url and url_name for create、update and delete view
        default url_name is classname_name
        """
        class_name = cls.get_class_name()
        if django.VERSION >= (2, 0):
            return path('{}/'.format(class_name), include([
                path('popup/', cls.create().as_view(), name='{}_popup_create'.format(class_name)),
                path('popup/<int:pk>/', cls.update().as_view(), name='{}_popup_update'.format(class_name)),
                path('popup/delete/<int:pk>/', cls.delete().as_view(), name='{}_popup_delete'.format(class_name)),
            ]))
        else:
            return url(r'^{}/'.format(class_name), include([
                url(r'^popup/$', cls.create().as_view(), name='{}_popup_create'.format(class_name)),
                url(r'^popup/(?P<pk>\d+)/$', cls.update().as_view(), name='{}_popup_update'.format(class_name)),
                url(r'^popup/delete/(?P<pk>\d+)/$', cls.delete().as_view(), name='{}_popup_delete'.format(class_name)),
            ])) 
Example 3
Project: django-rest-autogen   Author: VackarAfzal   File: registration.py    MIT License 6 votes vote down vote up
def register_router(
        router,
        urlpatterns,
        api_url='site-api',
        version=1,
        namespace='site_api',
        open_api_suffix='open-api',
        open_api_title='Site API'
):
    logger.info('Registering router under namespace: {0}'.format(namespace))
    urlpatterns += [
        url(r'^{0}/v{1}/?'.format(api_url, version), include(router.urls, namespace=namespace)),
        url(r'^{0}/v{1}/{2}/?'.format(api_url, version, open_api_suffix), get_swagger_view(title=open_api_title)),
    ]

    return urlpatterns 
Example 4
Project: django-binder   Author: CodeYellowBV   File: test_router.py    MIT License 6 votes vote down vote up
def test_register_adds_default_routes_from_modelname(self):
		class ParentView(ModelView):
			pass

		class FooView(ParentView):
			model = FooModel

		class BarView(ParentView):
			model = BarModel

		r = Router()
		r.register(ParentView)
		urls_module.urlpatterns = [url(r'^', include(r.urls))]

		self.assertTrue(is_valid_path('/foo_model/', urls_module))
		self.assertTrue(is_valid_path('/foo_model/1/', urls_module))
		self.assertTrue(is_valid_path('/bar_model/12345/', urls_module))
		self.assertFalse(is_valid_path('/bar_model/lalala/', urls_module))
		self.assertFalse(is_valid_path('/another_model/', urls_module)) 
Example 5
Project: django-binder   Author: CodeYellowBV   File: test_router.py    MIT License 6 votes vote down vote up
def test_register_adds_custom_route_names(self):
		class ParentView(ModelView):
			pass

		class FooView(ParentView):
			model = FooModel
			route = 'foo'

		class BarView(ParentView):
			model = BarModel
			# Explicit Route objects should also be accepted
			route = Route('bar')

		r = Router()
		r.register(ParentView)
		urls_module.urlpatterns = [url(r'^', include(r.urls))]

		self.assertTrue(is_valid_path('/foo/', urls_module))
		self.assertTrue(is_valid_path('/foo/1/', urls_module))
		self.assertTrue(is_valid_path('/bar/12345/', urls_module))

		# Default named routes should not be there
		self.assertFalse(is_valid_path('/foo_model/1/', urls_module))
		self.assertFalse(is_valid_path('/bar_model/1/', urls_module)) 
Example 6
Project: django-binder   Author: CodeYellowBV   File: test_router.py    MIT License 6 votes vote down vote up
def test_register_obeys_custom_route_config(self):
		class ParentView(ModelView):
			pass

		class FooView(ParentView):
			model = FooModel
			route = Route('foo', list_endpoint=False)

		class BarView(ParentView):
			model = BarModel
			route = Route('bar', detail_endpoint=False)

		r = Router()
		r.register(ParentView)
		urls_module.urlpatterns = [url(r'^', include(r.urls))]

		self.assertFalse(is_valid_path('/foo/', urls_module))
		self.assertTrue(is_valid_path('/foo/1/', urls_module))

		self.assertTrue(is_valid_path('/bar/', urls_module))
		self.assertFalse(is_valid_path('/bar/1/', urls_module)) 
Example 7
Project: scale   Author: ngageoint   File: rest.py    Apache License 2.0 6 votes vote down vote up
def check_update(request, fields):
    """Checks whether the given request includes fields that are not allowed to be updated.

    :param request: The context of an active HTTP request.
    :type request: :class:`rest_framework.request.Request`
    :param fields: A list of field names that are permitted.
    :type fields: [string]
    :returns: True when the request does not include extra fields.
    :rtype: bool

    :raises :class:`util.rest.ReadOnly`: If the request includes unsupported fields to update.
    :raises :class:`exceptions.AssertionError`: If fields in not a list or None.
    """
    fields = fields or []
    assert (isinstance(fields, list))
    extra = filter(lambda x, y=fields: x not in y, request.data.keys())
    if extra:
        raise ReadOnly('Fields do not allow updates: %s' % ', '.join(extra))
    return True 
Example 8
Project: edunext-ecommerce   Author: eduNEXT   File: app.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_urls(self):
        urls = [
            url(r'^$', self.index_view.as_view(), name='index'),
            url(r'^catalogue/', include(self.catalogue_app.urls)),
            url(r'^reports/', include(self.reports_app.urls)),
            url(r'^orders/', include(self.orders_app.urls)),
            url(r'^users/', include(self.users_app.urls)),
            url(r'^content-blocks/', include(self.promotions_app.urls)),
            url(r'^pages/', include(self.pages_app.urls)),
            url(r'^partners/', include(self.partners_app.urls)),
            url(r'^offers/', include(self.offers_app.urls)),
            url(r'^ranges/', include(self.ranges_app.urls)),
            url(r'^reviews/', include(self.reviews_app.urls)),
            url(r'^vouchers/', include(self.vouchers_app.urls)),
            url(r'^comms/', include(self.comms_app.urls)),
            url(r'^shipping/', include(self.shipping_app.urls)),
            url(r'^refunds/', include(self.refunds_app.urls)),
        ]
        urls += AUTH_URLS
        return self.post_process_urls(urls) 
Example 9
Project: lepo   Author: akx   File: utils.py    MIT License 6 votes vote down vote up
def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
    # NB: This could just as well be your `urls.py` – it's here to make testing various handler
    #     configurations easier.

    router = Router.from_file(os.path.join(os.path.dirname(__file__), 'tests', definition_file))
    router.add_handlers(handler_module)
    validate_router(router)
    router_urls = router.get_urls(
        decorate=(csrf_exempt,),
        optional_trailing_slash=True,
        root_view_name='api_root',
    )

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^api/', include((router_urls, 'api'), 'api')),
        url(r'^api/', include((get_docs_urls(router, 'api-docs'), 'api-docs'), 'api-docs')),
    ]
    return urlpatterns 
Example 10
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import(self):
        urls = patterns('', url(r'api/base/path/', include(self.url_patterns)))
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(len(self.url_patterns), len(apis)) 
Example 11
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_format_api_patterns_excluded_namesapce(self):
        urls = patterns(
            '',
            url(r'api/base/path/',
                include(self.url_patterns, namespace='exclude'))
        )
        apis = self.urlparser.format_api_patterns(
            url_patterns=urls, exclude_namespaces='exclude')

        self.assertEqual([], apis) 
Example 12
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import_with_routers(self):

        class MockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        class AnotherMockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        router = DefaultRouter()
        router.register(r'other_views', MockApiViewSet, base_name='test_base_name')
        router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name')

        urls_app = patterns('', url(r'^', include(router.urls)))
        urls = patterns(
            '',
            url(r'api/', include(urls_app)),
            url(r'test/', include(urls_app))
        )
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(
            4, sum(api['path'].find('api') != -1 for api in apis))
        self.assertEqual(
            4, sum(api['path'].find('test') != -1 for api in apis)) 
Example 13
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def setUp(self):
        class FuzzyApiView(APIView):
            def get(self, request):
                pass

        class ShinyApiView(APIView):
            def get(self, request):
                pass

        api_fuzzy_url_patterns = patterns(
            '', url(r'^item/$', FuzzyApiView.as_view(), name='find_me'))
        api_shiny_url_patterns = patterns(
            '', url(r'^item/$', ShinyApiView.as_view(), name='hide_me'))

        fuzzy_app_urls = patterns(
            '', url(r'^api/', include(api_fuzzy_url_patterns,
                                      namespace='api_fuzzy_app')))
        shiny_app_urls = patterns(
            '', url(r'^api/', include(api_shiny_url_patterns,
                                      namespace='api_shiny_app')))

        self.project_urls = patterns(
            '',
            url('my_fuzzy_app/', include(fuzzy_app_urls)),
            url('my_shiny_app/', include(shiny_app_urls)),
        ) 
Example 14
Project: django-subadmin   Author: inueni   File: __init__.py    MIT License 5 votes vote down vote up
def get_subadmin_urls(self):
        urlpatterns = []

        for modeladmin in self.subadmin_instances:
            regex = r'^(.+)/%s/' % modeladmin.model._meta.model_name

            urls = [
                url(regex , include(modeladmin.urls))
            ]

            urlpatterns += urls
        
        return urlpatterns 
Example 15
Project: wagtailplus   Author: MechanisM   File: wagtail_hooks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^addresses/', include(admin_urls)),
    ] 
Example 16
Project: wagtailplus   Author: MechanisM   File: wagtail_hooks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^wagtail-events/', include(admin_urls)),
    ] 
Example 17
Project: wagtailplus   Author: MechanisM   File: wagtail_hooks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^contacts/', include(admin_urls)),
    ] 
Example 18
Project: wagtailplus   Author: MechanisM   File: wagtail_hooks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^links/', include(admin_urls)),
    ] 
Example 19
Project: wagtail-relevancy   Author: neon-jungle   File: wagtail_hooks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^relevancy/', include(urls)),
    ] 
Example 20
Project: litmus-site   Author: alps-jbnu   File: urls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def paged_list_view(view, name):
    return include([
        url(r'^$', view.as_view(), name=name),
        url(r'^(?P<page>\d+)$', view.as_view(), name=name),
    ]) 
Example 21
Project: wagtailinvoices   Author: SableWalnut   File: wagtail_hooks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^invoices/', include(urls)),
    ] 
Example 22
Project: wagtailjobs   Author: SableWalnut   File: wagtail_hooks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^jobs/', include(urls)),
    ] 
Example 23
Project: cosinnus-core   Author: wechange-eg   File: urls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def ready(self):
        with self.lock:
            if not self.is_ready:
                self._api_urlpatterns = [
                    url(r'', include('cosinnus.urls_api'))
                ]
                self.is_ready = True 
Example 24
Project: cosinnus-core   Author: wechange-eg   File: urls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def register(self, app, root_patterns=None, group_patterns=None,
                 api_patterns=None, url_app_name_override=None):
        with self.lock:
            try:
                app_name = app_registry.get_name(app)
            except KeyError:
                raise ImproperlyConfigured('You need to register the app "%s" '
                    'before you can use it to build URLs.' % app)
            if app in self._apps:
                return
            self._apps.add(app)
            
            # group patterns are added for each group model, using the url key of the group model,
            # setting to the group base url of that model,
            # and modifying the URL pattern name with the registered group model prefix!
            if group_patterns:
                url_app_name = url_app_name_override or app_name
                patterns_copy = []
                for url_key in group_model_registry:
                    url_base = r'^%s/(?P<group>[^/]+)/%s/' % (url_key, url_app_name)
                    for patt in group_patterns:
                        patterns_copy.append(url(url_base+patt.pattern._regex[1:], patt.callback, patt.default_args, name=group_model_registry.get_url_name_prefix(url_key, '') + patt.name))
                
                self._urlpatterns += [
                    url('', include((patterns_copy, app_name), namespace=app_name)),
                ]
            if root_patterns:
                self._urlpatterns += [
                    url(r'', include(root_patterns))
                ]
            if api_patterns:
                self._api_urlpatterns += [
                    url(r'^', include((api_patterns, app_name), namespace=app_name)),
                ] 
Example 25
Project: wagtail_video   Author: l1f7   File: wagtail_hooks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^video/', include((admin_urls, 'wagtail_video'), namespace='wagtail_video')),
    ] 
Example 26
Project: ashmont-valley-website   Author: Ashmont-Valley   File: urls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def url_tree(regex, *urls):
    return url(regex, include(patterns('', *urls))) 
Example 27
Project: ashmont-valley-website   Author: Ashmont-Valley   File: urls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def url_tree(regex, view='', *urls):
    return url(regex, include(patterns(view, *urls))) 
Example 28
Project: ashmont-valley-website   Author: Ashmont-Valley   File: urls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def url_tree(regex, *urls):
    return url(regex, include(patterns('', *urls))) 
Example 29
Project: ops22   Author: spark8103   File: sites.py    MIT License 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = patterns('',
                               url(r'^jsi18n/$', wrap(self.i18n_javascript,
                                                      cacheable=True), name='jsi18n')
                               )

        # Registed admin views
        urlpatterns += patterns('',
                                *[url(
                                  path, wrap(self.create_admin_view(clz_or_func)) if type(clz_or_func) == type and issubclass(clz_or_func, BaseAdminView) else include(clz_or_func(self)),
                                  name=name) for path, clz_or_func, name in self._registry_views]
                                )

        # Add in each model's views.
        for model, admin_class in self._registry.iteritems():
            view_urls = [url(
                path, wrap(
                    self.create_model_admin_view(clz, model, admin_class)),
                name=name % (model._meta.app_label, model._meta.model_name))
                for path, clz, name in self._registry_modelviews]
            urlpatterns += patterns('',
                                    url(
                                    r'^%s/%s/' % (
                                        model._meta.app_label, model._meta.model_name),
                                    include(patterns('', *view_urls)))
                                    )

        return urlpatterns 
Example 30
Project: evm   Author: gdgnewdelhi   File: urls.py    MIT License 5 votes vote down vote up
def default_urlpatterns(provider):

    urlpatterns = patterns(provider.package + '.views',
                           url('^login/$', 'oauth_login',
                               name=provider.id + "_login"),
                           url('^login/callback/$', 'oauth_callback',
                               name=provider.id + "_callback"))

    return patterns('', url('^' + provider.id + '/', include(urlpatterns))) 
Example 31
Project: evm   Author: gdgnewdelhi   File: urls.py    MIT License 5 votes vote down vote up
def default_urlpatterns(provider):
    urlpatterns = patterns(provider.package + '.views',
                           url('^login/$', 'oauth2_login',
                               name=provider.id + "_login"),
                           url('^login/callback/$', 'oauth2_callback',
                               name=provider.id + "_callback"))

    return patterns('', url('^' + provider.id + '/', include(urlpatterns))) 
Example 32
Project: django-utils-plus   Author: jnoortheen   File: router.py    MIT License 5 votes vote down vote up
def incl(self, module, namespace=None, prefix=None, **kwargs):
        """
            This is gives a way to handle the standard include functionality.

            # original
            urlpatterns = [
                url(r'^document/', include('document.urls')),
                url(r'^core/', include('core.urls', namespace='core'), {'kwarg1':'kwval1', }),
            ]
            into this

            # using Url
            with Url('document') as u:
                u.incl('document.urls')
            u.incl('core.urls', 'core', kwarg1='kwval1', prefix='core')
            urlpatterns = u.urlpatterns
        Args:
            module (str, list): module denoted as string or a list of urls
            namespace (str): namespace for the included urls
        """
        if prefix: self._paths.append(prefix)

        paths = self.__get_path()
        regex = '^' + paths + '/'
        urlconf_module, app_name, namespace = include(module, namespace=namespace)
        self.urlpatterns.append(RegexURLResolver(regex, urlconf_module, kwargs, app_name, namespace))

        if prefix: self._last_path = self._paths.pop() 
Example 33
Project: refarm-site   Author: fidals   File: sites.py    MIT License 5 votes vote down vote up
def get_urls(self):
        original_urls = super(SiteWithTableEditor, self).get_urls()

        return [
            url(
                r'^editor/$',
                self.admin_view(self.table_editor_view.as_view(each_context=self.each_context)),
                name='editor'
            ),
            url(r'^select2/', include('django_select2.urls')),
            *original_urls
        ] 
Example 34
Project: mudong_blog   Author: mudong1991   File: sites.py    GNU General Public License v2.0 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = patterns('',
                               url(r'^jsi18n/$', wrap(self.i18n_javascript,
                                                      cacheable=True), name='jsi18n')
                               )

        # Registed admin views
        urlpatterns += patterns('',
                                *[url(
                                  path, wrap(self.create_admin_view(clz_or_func)) if type(clz_or_func) == type and issubclass(clz_or_func, BaseAdminView) else include(clz_or_func(self)),
                                  name=name) for path, clz_or_func, name in self._registry_views]
                                )

        # Add in each model's views.
        for model, admin_class in self._registry.iteritems():
            view_urls = [url(
                path, wrap(
                    self.create_model_admin_view(clz, model, admin_class)),
                name=name % (model._meta.app_label, model._meta.module_name))
                for path, clz, name in self._registry_modelviews]
            urlpatterns += patterns('',
                                    url(
                                    r'^%s/%s/' % (
                                        model._meta.app_label, model._meta.module_name),
                                    include(patterns('', *view_urls)))
                                    )

        return urlpatterns 
Example 35
Project: wagtail-import-export-tool   Author: berkalpyakici   File: wagtail_hooks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    """
    Register 'import-export/' url path to admin urls.
    """
    return [
        url(r'^import-export/', include(admin_urls, namespace='wagtailimportexport')),
    ] 
Example 36
Project: wagtail-personalisation   Author: wagtail   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def register_admin_urls():
    """Adds the administration urls for the personalisation apps."""
    return [
        url(r'^personalisation/', include(
            admin_urls, namespace='wagtail_personalisation')),
    ] 
Example 37
Project: substra-backend   Author: SubstraFoundation   File: views.py    Apache License 2.0 5 votes vote down vote up
def schema_view(request):
    generator = SchemaGenerator(
        title='Substra Backend API',
        patterns=[url(r'^/', include([url(r'^', include(router.urls))]))])
    return response.Response(generator.get_schema(request=request)) 
Example 38
Project: site   Author: alphageek-xyz   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        urls = super(AGCSForumApp, self).get_urls()
        return urls + [
            url(r'^account/', include(self.auth_app.urls)),
        ] 
Example 39
Project: site   Author: alphageek-xyz   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        return [
            url(r'^', include('django.contrib.auth.urls')),
            url(r'^parameters/edit/', self.user_parameters_update_view.as_view(), name='account-parameters'),
            url(r'^password/edit/', self.user_password_update_view.as_view(), name='account-password'),
            url(r'^register/', self.user_create_view.as_view(), name='register'),
            url(r'^unregister/$', self.user_delete_view.as_view(), name='unregister'),
        ] 
Example 40
Project: django-admino   Author: erdem   File: sites.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urlpatterns = super(AdminoSite, self).get_urls()
        valid_app_labels = []
        for model, model_admin in self._registry.items():
            api_urlpatterns = [
                url(r'^api/%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.api_urls)),
            ]
            urlpatterns = urlpatterns + api_urlpatterns
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)
        return urlpatterns 
Example 41
Project: wagtailembedder   Author: springload   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^classembedder/', include(urls)),
    ] 
Example 42
Project: scale   Author: ngageoint   File: rest.py    Apache License 2.0 5 votes vote down vote up
def get_versioned_urls(apps):
    """Generates a list of URLs for applications with REST APIs

    :param apps: A list of application names to register.
    :type apps: [string]
    :returns: A list of URLs for REST APIs with version prefixes.
    :rtype: [:class:`django.core.urlresolvers.RegexURLPattern`]
    """
    urls = []

    # Check whether the application is configured to use versions
    rest_settings = getattr(settings, 'REST_FRAMEWORK', None)
    if not rest_settings:
        return urls
    allowed_versions = rest_settings.get('ALLOWED_VERSIONS', None)
    if not allowed_versions:
        return urls

    # Generate a URL for each endpoint with a version prefix
    for version in allowed_versions:
        app_urls = []
        for app in apps:
            app_urls.append(url('', include(app + '.urls')))

        urls.append(url(r'^' + version + '/', include(app_urls, namespace=version)))
    return urls 
Example 43
Project: scale   Author: ngageoint   File: rest.py    Apache License 2.0 5 votes vote down vote up
def parse_datetime(request, name, default_value=None, required=True):
    """Parses a datetime parameter from the given request.

    :param request: The context of an active HTTP request.
    :type request: :class:`rest_framework.request.Request`
    :param name: The name of the parameter to parse.
    :type name: string
    :param default_value: The name of the parameter to parse.
    :type default_value: datetime.datetime
    :param required: Indicates whether or not the parameter is required. An exception will be raised if the parameter
        does not exist, there is no default value, and required is True.
    :type required: bool
    :returns: The value of the named parameter or the default value if provided.
    :rtype: datetime.datetime

    :raises :class:`util.rest.BadParameter`: If the value cannot be parsed.
    """
    value = _get_param(request, name, default_value, required)
    if not isinstance(value, basestring):
        return value

    try:
        result = parse_util.parse_datetime(value)
        if result:
            return result
        raise BadParameter('Did not parse a result for parameter: %s' % name)
    except:
        raise BadParameter('Datetime values must follow ISO-8601 and include a timezone: %s' % name) 
Example 44
Project: taiga-back-   Author: andyzsf   File: urlpatterns.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
    ret = []
    for urlpattern in urlpatterns:
        if isinstance(urlpattern, RegexURLResolver):
            # Set of included URL patterns
            regex = urlpattern.regex.pattern
            namespace = urlpattern.namespace
            app_name = urlpattern.app_name
            kwargs = urlpattern.default_kwargs
            # Add in the included patterns, after applying the suffixes
            patterns = apply_suffix_patterns(urlpattern.url_patterns,
                                             suffix_pattern,
                                             suffix_required)
            ret.append(url(regex, include(patterns, namespace, app_name), kwargs))

        else:
            # Regular URL pattern
            regex = urlpattern.regex.pattern.rstrip("$") + suffix_pattern
            view = urlpattern._callback or urlpattern._callback_str
            kwargs = urlpattern.default_args
            name = urlpattern.name
            # Add in both the existing and the new urlpattern
            if not suffix_required:
                ret.append(urlpattern)
            ret.append(url(regex, view, kwargs, name))

    return ret 
Example 45
Project: taiga-back-   Author: andyzsf   File: urlpatterns.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
    """
    Supplement existing urlpatterns with corresponding patterns that also
    include a ".format" suffix.  Retains urlpattern ordering.

    urlpatterns:
        A list of URL patterns.

    suffix_required:
        If `True`, only suffixed URLs will be generated, and non-suffixed
        URLs will not be used.  Defaults to `False`.

    allowed:
        An optional tuple/list of allowed suffixes.  eg ["json", "api"]
        Defaults to `None`, which allows any suffix.
    """
    suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG
    if allowed:
        if len(allowed) == 1:
            allowed_pattern = allowed[0]
        else:
            allowed_pattern = "(%s)" % "|".join(allowed)
        suffix_pattern = r"\.(?P<%s>%s)$" % (suffix_kwarg, allowed_pattern)
    else:
        suffix_pattern = r"\.(?P<%s>[a-z0-9]+)$" % suffix_kwarg

    return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required) 
Example 46
Project: taiga-back-   Author: andyzsf   File: apps.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def ready(self):
        if settings.FEEDBACK_ENABLED:
            from taiga.urls import urlpatterns
            from .routers import router
            urlpatterns.append(url(r'^api/v1/', include(router.urls))) 
Example 47
Project: taiga-back-   Author: andyzsf   File: apps.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def ready(self):
        from taiga.urls import urlpatterns
        urlpatterns.append(url(r'^api/v1/', include(router.urls))) 
Example 48
Project: gro-api   Author: OpenAgricultureFoundation   File: urls.py    GNU General Public License v2.0 5 votes vote down vote up
def get_current_urls():
    urls = BaseRouter.get_instance().urls + [
        url(r'^auth/', include(auth_patterns)),
        url(r'^auth/registration/', include(auth_registration_patterns)),
        url(r'^docs/', include('rest_framework_swagger.urls')),
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    if settings.DEBUG:
        import debug_toolbar
        urls.append(url(r'^__debug__/', include(debug_toolbar.urls)))
    return urls 
Example 49
Project: wagtailapproval   Author: absperf   File: wagtail_hooks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_admin_urls():
    return [url(r'^approval/', include(urls, namespace='wagtailapproval'))] 
Example 50
Project: mos-horizon   Author: Mirantis   File: base.py    Apache License 2.0 5 votes vote down vote up
def _decorated_urls(self):
        urlpatterns = self._get_default_urlpatterns()

        # Apply access controls to all views in the patterns
        permissions = getattr(self, 'permissions', [])
        _decorate_urlconf(urlpatterns, require_perms, permissions)
        _decorate_urlconf(urlpatterns, _current_component, panel=self)

        # Return the three arguments to django.conf.urls.include
        return urlpatterns, self.slug, self.slug