Python django.conf.settings.ROOT_URLCONF Examples

The following are 30 code examples for showing how to use django.conf.settings.ROOT_URLCONF(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: py2swagger   Author: Arello-Mobile   File: urlparser.py    License: MIT License 6 votes vote down vote up
def get_apis(self, url_patterns=None, urlconf=None, filter_path=None, exclude_namespaces=None):
        """
        Returns all the DRF APIViews found in the project URLs
        patterns -- supply list of patterns (optional)
        exclude_namespaces -- list of namespaces to ignore (optional)
        """

        if not url_patterns and urlconf:
            if isinstance(urlconf, six.string_types):
                urls = import_module(urlconf)
            else:
                urls = urlconf
            url_patterns = urls.urlpatterns
        elif not url_patterns and not urlconf:
            urls = import_module(settings.ROOT_URLCONF)
            url_patterns = urls.urlpatterns

        formatted_apis = self.format_api_patterns(
            url_patterns,
            filter_path=filter_path,
            exclude_namespaces=exclude_namespaces,
        )

        return formatted_apis 
Example 2
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 6 votes vote down vote up
def test_get_apis(self):
        urls = import_module(settings.ROOT_URLCONF)
        # Overwrite settings with test patterns
        urls.urlpatterns = self.url_patterns
        apis = self.urlparser.get_apis()
        self.assertEqual(self.url_patterns[0], apis[0]['pattern'])
        self.assertEqual('/a-view/', apis[0]['path'])
        self.assertEqual(self.url_patterns[1], apis[1]['pattern'])
        self.assertEqual('/b-view', apis[1]['path'])
        self.assertEqual(self.url_patterns[2], apis[2]['pattern'])
        self.assertEqual('/c-view/', apis[2]['path'])
        self.assertEqual(self.url_patterns[3], apis[3]['pattern'])
        self.assertEqual('/a-view/child/', apis[3]['path'])
        self.assertEqual(self.url_patterns[4], apis[4]['pattern'])
        self.assertEqual('/a-view/child2/', apis[4]['path'])
        self.assertEqual(self.url_patterns[5], apis[5]['pattern'])
        self.assertEqual('/another-view/', apis[5]['path'])
        self.assertEqual(self.url_patterns[6], apis[6]['pattern'])
        self.assertEqual('/view-with-param/{var}/', apis[6]['path']) 
Example 3
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 6 votes vote down vote up
def test_get_apis_urlconf(self):
        urls = import_module(settings.ROOT_URLCONF)
        # Overwrite settings with test patterns
        urls.urlpatterns = self.url_patterns
        apis = self.urlparser.get_apis(urlconf=urls)
        self.assertEqual(self.url_patterns[0], apis[0]['pattern'])
        self.assertEqual('/a-view/', apis[0]['path'])
        self.assertEqual(self.url_patterns[1], apis[1]['pattern'])
        self.assertEqual('/b-view', apis[1]['path'])
        self.assertEqual(self.url_patterns[2], apis[2]['pattern'])
        self.assertEqual('/c-view/', apis[2]['path'])
        self.assertEqual(self.url_patterns[3], apis[3]['pattern'])
        self.assertEqual('/a-view/child/', apis[3]['path'])
        self.assertEqual(self.url_patterns[4], apis[4]['pattern'])
        self.assertEqual('/a-view/child2/', apis[4]['path'])
        self.assertEqual(self.url_patterns[5], apis[5]['pattern'])
        self.assertEqual('/another-view/', apis[5]['path'])
        self.assertEqual(self.url_patterns[6], apis[6]['pattern'])
        self.assertEqual('/view-with-param/{var}/', apis[6]['path']) 
Example 4
Project: luscan-devel   Author: blackye   File: testcases.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _post_teardown(self):
        """ Performs any post-test things. This includes:

            * Putting back the original ROOT_URLCONF if it was changed.
            * Force closing the connection, so that the next test gets
              a clean cursor.
        """
        self._fixture_teardown()
        self._urlconf_teardown()
        # Some DB cursors include SQL statements as part of cursor
        # creation. If you have a test that does rollback, the effect
        # of these statements is lost, which can effect the operation
        # of tests (e.g., losing a timezone setting causing objects to
        # be created with the wrong time).
        # To make sure this doesn't happen, get a clean connection at the
        # start of every test.
        for conn in connections.all():
            conn.close() 
Example 5
Project: django-collaborative   Author: propublica   File: admin.py    License: MIT License 6 votes vote down vote up
def attempt_register(self, Model, ModelAdmin):
        try:
            admin.site.unregister(Model)
        except admin.sites.NotRegistered:
            pass
        try:
            admin.site.register(Model, ModelAdmin)
        except admin.sites.AlreadyRegistered:
            logger.warning("WARNING! %s admin already exists." % (
                str(Model)
            ))

        # If we don't do this, our module will show up in admin but
        # it will show up as an unclickable thing with on add/change
        importlib.reload(import_module(settings.ROOT_URLCONF))
        clear_url_caches() 
Example 6
Project: iguana   Author: iguana-project   File: test_login.py    License: Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def createTempViewURL():
    # add the TempView to the urlpatterns
    global urlpatterns
    urlpatterns += [
        url(r'^temp/?', TempView.as_view(), name='temp'),
    ]

    # reload the urlpatterns
    urlconf = settings.ROOT_URLCONF
    if urlconf in sys.modules:
        reload(sys.modules[urlconf])
    reloaded = import_module(urlconf)
    reloaded_urls = getattr(reloaded, 'urlpatterns')
    set_urlconf(tuple(reloaded_urls))

    # return the temporary URL
    return reverse('temp') 
Example 7
Project: django-is-core   Author: matllubos   File: tasks.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def background_serialization(self, exported_file_pk, rest_context, language, requested_fieldset, serialization_format,
                             filename, query):
    # Must be here, because handlers is not registered
    import_string(django_settings.ROOT_URLCONF)

    prev_language = translation.get_language()
    translation.activate(language)
    try:
        exported_file = self.get_exported_file(exported_file_pk)
        exported_file.file.save(filename, ContentFile(''))
        request = get_rest_request(exported_file.created_by, rest_context)
        if settings.BACKGROUND_EXPORT_TASK_UPDATE_REQUEST_FUNCTION:
            request = import_string(settings.BACKGROUND_EXPORT_TASK_UPDATE_REQUEST_FUNCTION)(request)
        query = string_to_obj(query)
        queryset = query.model.objects.all()
        queryset.query = query
        FileBackgroundExportGenerator(query.model).generate(
            exported_file, request, queryset, RFS.create_from_string(requested_fieldset), serialization_format
        )
    finally:
        translation.activate(prev_language) 
Example 8
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        ret = {}

        # Get the version namespace
        namespace = getattr(request.resolver_match, "namespace", "")
        for ns in namespace.split(":"):
            if re.match(r"v[0-9]+", ns, re.I):
                namespace = ns
                break

        if self.urlconf:
            urlconf = self.urlconf
        else:
            urlconf = import_module(settings.ROOT_URLCONF)
        endpoints = get_api_endpoints(urlconf.urlpatterns)

        for endpoint in sorted(endpoints, key=lambda e: e["pattern"].name):
            name = endpoint["pattern"].name
            if endpoint["method"] == "GET" and namespace in endpoint["namespace"].split(":"):
                allow_cdn = getattr(endpoint["pattern"], "allow_cdn", True)

                if not allow_cdn and settings.APP_SERVER_URL:
                    base = settings.APP_SERVER_URL
                else:
                    base = request.build_absolute_uri()

                try:
                    full_name = (
                        f'{endpoint["namespace"]}:{name}' if endpoint["namespace"] else name
                    )
                    path = reverse(full_name, *args, **kwargs)
                except NoReverseMatch:
                    continue

                full_url = urljoin(base, path)
                ret[name] = full_url

        return Response(ret) 
Example 9
Project: GTDWeb   Author: lanbing510   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _pre_setup(self):
        """Performs any pre-test setup. This includes:

        * Creating a test client.
        * If the class has a 'urls' attribute, replace ROOT_URLCONF with it.
        * Clearing the mail test outbox.
        """
        self.client = self.client_class()
        self._urlconf_setup()
        mail.outbox = [] 
Example 10
Project: GTDWeb   Author: lanbing510   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _urlconf_setup(self):
        if hasattr(self, 'urls'):
            warnings.warn(
                "SimpleTestCase.urls is deprecated and will be removed in "
                "Django 1.10. Use @override_settings(ROOT_URLCONF=...) "
                "in %s instead." % self.__class__.__name__,
                RemovedInDjango110Warning, stacklevel=2)
            set_urlconf(None)
            self._old_root_urlconf = settings.ROOT_URLCONF
            settings.ROOT_URLCONF = self.urls
            clear_url_caches() 
Example 11
Project: GTDWeb   Author: lanbing510   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _post_teardown(self):
        """Performs any post-test things. This includes:

        * Putting back the original ROOT_URLCONF if it was changed.
        """
        self._urlconf_teardown() 
Example 12
Project: GTDWeb   Author: lanbing510   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _urlconf_teardown(self):
        if hasattr(self, '_old_root_urlconf'):
            set_urlconf(None)
            settings.ROOT_URLCONF = self._old_root_urlconf
            clear_url_caches() 
Example 13
Project: GTDWeb   Author: lanbing510   File: urlresolvers.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_resolver(urlconf):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return RegexURLResolver(r'^/', urlconf) 
Example 14
Project: django-rest-framework-docs   Author: manosim   File: api_docs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, drf_router=None):
        self.endpoints = []
        self.drf_router = drf_router
        try:
            root_urlconf = import_string(settings.ROOT_URLCONF)
        except ImportError:
            # Handle a case when there's no dot in ROOT_URLCONF
            root_urlconf = import_module(settings.ROOT_URLCONF)
        if hasattr(root_urlconf, 'urls'):
            self.get_all_view_names(root_urlconf.urls.urlpatterns)
        else:
            self.get_all_view_names(root_urlconf.urlpatterns) 
Example 15
Project: bioforum   Author: reBiocoder   File: locale.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example 16
Project: bioforum   Author: reBiocoder   File: locale.py    License: MIT License 5 votes vote down vote up
def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(request.path_info)
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)

        if (response.status_code == 404 and not language_from_path and
                i18n_patterns_used and prefixed_default_language):
            # Maybe the language code is missing in the URL? Try adding the
            # language prefix and redirecting to that URL.
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            path_needs_slash = (
                not path_valid and (
                    settings.APPEND_SLASH and not language_path.endswith('/') and
                    is_valid_path('%s/' % language_path, urlconf)
                )
            )

            if path_valid or path_needs_slash:
                script_prefix = get_script_prefix()
                # Insert language after the script prefix and before the
                # rest of the URL
                language_url = request.get_full_path(force_append_slash=path_needs_slash).replace(
                    script_prefix,
                    '%s%s/' % (script_prefix, language),
                    1
                )
                return self.response_redirect_class(language_url)

        if not (i18n_patterns_used and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response 
Example 17
Project: bioforum   Author: reBiocoder   File: resolvers.py    License: MIT License 5 votes vote down vote up
def get_resolver(urlconf=None):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return URLResolver(RegexPattern(r'^/'), urlconf) 
Example 18
Project: django-seo   Author: whyflyru   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _reload_urlconf():
    """
    Reload Django URL configuration and clean caches
    """
    module = importlib.import_module(settings.ROOT_URLCONF)
    if six.PY2:
        reload(module)
    else:
        importlib.reload(module)
    clear_url_caches() 
Example 19
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: locale.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example 20
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: locale.py    License: MIT License 5 votes vote down vote up
def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(request.path_info)
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)

        if (response.status_code == 404 and not language_from_path and
                i18n_patterns_used and prefixed_default_language):
            # Maybe the language code is missing in the URL? Try adding the
            # language prefix and redirecting to that URL.
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            path_needs_slash = (
                not path_valid and (
                    settings.APPEND_SLASH and not language_path.endswith('/') and
                    is_valid_path('%s/' % language_path, urlconf)
                )
            )

            if path_valid or path_needs_slash:
                script_prefix = get_script_prefix()
                # Insert language after the script prefix and before the
                # rest of the URL
                language_url = request.get_full_path(force_append_slash=path_needs_slash).replace(
                    script_prefix,
                    '%s%s/' % (script_prefix, language),
                    1
                )
                return self.response_redirect_class(language_url)

        if not (i18n_patterns_used and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        response.setdefault('Content-Language', language)
        return response 
Example 21
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: resolvers.py    License: MIT License 5 votes vote down vote up
def get_resolver(urlconf=None):
    if urlconf is None:
        urlconf = settings.ROOT_URLCONF
    return URLResolver(RegexPattern(r'^/'), urlconf) 
Example 22
Project: openapi-core   Author: p1c2u   File: test_django.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def django_settings(self):
        import django
        from django.conf import settings
        from django.contrib import admin
        from django.urls import path

        if settings.configured:
            return

        settings.configure(
            ALLOWED_HOSTS=[
                'testserver',
            ],
            INSTALLED_APPS=[
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.messages',
                'django.contrib.sessions',
            ],
            MIDDLEWARE=[
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
            ]
        )
        django.setup()
        settings.ROOT_URLCONF = (
            path('admin/', admin.site.urls),
        ) 
Example 23
Project: python   Author: Yeah-Kun   File: locale.py    License: Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example 24
Project: python   Author: Yeah-Kun   File: locale.py    License: Apache License 2.0 5 votes vote down vote up
def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(request.path_info)
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)

        if (response.status_code == 404 and not language_from_path and
                i18n_patterns_used and prefixed_default_language):
            # Maybe the language code is missing in the URL? Try adding the
            # language prefix and redirecting to that URL.
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            path_needs_slash = (
                not path_valid and (
                    settings.APPEND_SLASH and not language_path.endswith('/') and
                    is_valid_path('%s/' % language_path, urlconf)
                )
            )

            if path_valid or path_needs_slash:
                script_prefix = get_script_prefix()
                # Insert language after the script prefix and before the
                # rest of the URL
                language_url = request.get_full_path(force_append_slash=path_needs_slash).replace(
                    script_prefix,
                    '%s%s/' % (script_prefix, language),
                    1
                )
                return self.response_redirect_class(language_url)

        if not (i18n_patterns_used and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response 
Example 25
Project: python   Author: Yeah-Kun   File: resolvers.py    License: Apache License 2.0 5 votes vote down vote up
def get_resolver(urlconf=None):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return RegexURLResolver(r'^/', urlconf) 
Example 26
Project: luscan-devel   Author: blackye   File: debug.py    License: GNU General Public License v2.0 5 votes vote down vote up
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if not tried:
            # tried exists but is an empty list. The URLconf must've been empty.
            return empty_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path_info[1:], # Trim leading slash
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html') 
Example 27
Project: luscan-devel   Author: blackye   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _pre_setup(self):
        """Performs any pre-test setup. This includes:

            * Flushing the database.
            * If the Test Case class has a 'fixtures' member, installing the
              named fixtures.
            * If the Test Case class has a 'urls' member, replace the
              ROOT_URLCONF with it.
            * Clearing the mail test outbox.
        """
        self.client = self.client_class()
        self._fixture_setup()
        self._urlconf_setup()
        mail.outbox = [] 
Example 28
Project: luscan-devel   Author: blackye   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _urlconf_setup(self):
        if hasattr(self, 'urls'):
            self._old_root_urlconf = settings.ROOT_URLCONF
            settings.ROOT_URLCONF = self.urls
            clear_url_caches() 
Example 29
Project: luscan-devel   Author: blackye   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _urlconf_teardown(self):
        if hasattr(self, '_old_root_urlconf'):
            settings.ROOT_URLCONF = self._old_root_urlconf
            clear_url_caches() 
Example 30
Project: openhgsenti   Author: drexly   File: testcases.py    License: Apache License 2.0 5 votes vote down vote up
def _pre_setup(self):
        """Performs any pre-test setup. This includes:

        * Creating a test client.
        * If the class has a 'urls' attribute, replace ROOT_URLCONF with it.
        * Clearing the mail test outbox.
        """
        self.client = self.client_class()
        self._urlconf_setup()
        mail.outbox = []