Python django.conf.settings.ROOT_URLCONF Examples

The following are 30 code examples of django.conf.settings.ROOT_URLCONF(). 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 also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: test_urlparser.py    From py2swagger with 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 #2
Source File: test_login.py    From iguana with 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 #3
Source File: admin.py    From django-collaborative with 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 #4
Source File: testcases.py    From luscan-devel with 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
Source File: tasks.py    From django-is-core with 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 #6
Source File: urlparser.py    From py2swagger with 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 #7
Source File: test_urlparser.py    From py2swagger with 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 #8
Source File: multihost.py    From django_render with Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        try:
            host = request.META["HTTP_HOST"]
            if host[-3:] == ":80":
                host = host[:-3]  # ignore default port number, if present
            request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
        except KeyError:
            pass  # use default urlconf (settings.ROOT_URLCONF) 
Example #9
Source File: testcases.py    From openhgsenti with Apache License 2.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 #10
Source File: testcases.py    From openhgsenti with Apache License 2.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 #11
Source File: test_views.py    From credentials with GNU Affero General Public License v3.0 5 votes vote down vote up
def _reload_urlconf(self):
        """ Helper method to reload url config."""
        imp.reload(sys.modules[settings.ROOT_URLCONF])
        clear_url_caches() 
Example #12
Source File: initialize.py    From cmdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
def delete_table(table):
    for url in data_url_map[table.name]:
        index = data.urls.urlpatterns.index(url)
        del data.urls.urlpatterns[index]

    for url in record_data_url_map[table.name]:
        index = record_data.urls.urlpatterns.index(url)
        del record_data.urls.urlpatterns[index]

    for url in deleted_data_url_map[table.name]:
        index = deleted_data.urls.urlpatterns.index(url)
        del deleted_data.urls.urlpatterns[index]

    # 更新url
    # url_conf.url_conf_manager.update_urlpatterns(getattr(import_module(settings.ROOT_URLCONF), "urlpatterns"))
    get_resolver.cache_clear()

    # 删除ES index
    delete_index(table.name)
    delete_index(table.name + ".")
    delete_index(table.name + "..")

    # 删除permission
    permission = models.Permission.objects.get(name=f"{table.name}.read")
    permission.delete()
    permission = models.Permission.objects.get(name=f"{table.name}.write")
    permission.delete()



# 启动时添加read_all 和 write_all权限 
Example #13
Source File: locale.py    From python2017 with 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 #14
Source File: locale.py    From python2017 with 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 #15
Source File: resolvers.py    From python2017 with 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 RegexURLResolver(r'^/', urlconf) 
Example #16
Source File: routers.py    From onlinestudy with MIT License 5 votes vote down vote up
def get_all_url_dict():
    url_order_dict = OrderedDict()
    root = import_string(settings.ROOT_URLCONF)
    recursive_url(None, '/', root.urlpatterns, url_order_dict)
    return url_order_dict 
Example #17
Source File: models.py    From django-collaborative with MIT License 5 votes vote down vote up
def model_cleanup(self):
        create_models()
        importlib.reload(import_module(settings.ROOT_URLCONF))
        app_config = apps.get_app_config("django_models_from_csv")
        hydrate_models_and_permissions(app_config)
        apps.clear_cache()
        clear_url_caches() 
Example #18
Source File: testcases.py    From openhgsenti with Apache License 2.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 #19
Source File: middleware.py    From scout_apm_python with MIT License 5 votes vote down vote up
def track_request_view_data(request, tracked_request):
    path = request.path
    tracked_request.tag(
        "path",
        create_filtered_path(
            path, [(k, v) for k, vs in request.GET.lists() for v in vs]
        ),
    )
    if ignore_path(path):
        tracked_request.tag("ignore_transaction", True)

    try:
        # Determine a remote IP to associate with the request. The value is
        # spoofable by the requester so this is not suitable to use in any
        # security sensitive context.
        user_ip = (
            request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")[0]
            or request.META.get("HTTP_CLIENT_IP", "").split(",")[0]
            or request.META.get("REMOTE_ADDR", None)
        )
        tracked_request.tag("user_ip", user_ip)
    except Exception:
        pass

    user = getattr(request, "user", None)
    if user is not None:
        try:
            tracked_request.tag("username", user.get_username())
        except Exception:
            pass

    tracked_request.tag("urlconf", get_urlconf(settings.ROOT_URLCONF)) 
Example #20
Source File: finders.py    From django-plotly-dash with MIT License 5 votes vote down vote up
def __init__(self):

        # Ensure urls are loaded
        root_urls = settings.ROOT_URLCONF
        importlib.import_module(root_urls)

        # Get all registered django dash apps

        self.apps = all_apps()

        self.locations = []
        self.storages = OrderedDict()

        self.ignore_patterns = ["*.py", "*.pyc",]

        added_locations = {}

        for app_slug, obj in self.apps.items():

            caller_module = obj.caller_module
            location = obj.caller_module_location
            subdir = obj.assets_folder

            path_directory = os.path.join(os.path.dirname(location), subdir)

            if os.path.isdir(path_directory):

                component_name = app_slug
                storage = FileSystemStorage(location=path_directory)
                path = full_asset_path(obj.caller_module.__name__,"")
                storage.prefix = path

                self.locations.append(component_name)
                self.storages[component_name] = storage

        super(DashAssetFinder, self).__init__()

    #pylint: disable=redefined-builtin 
Example #21
Source File: settings.py    From django-sae with Apache License 2.0 5 votes vote down vote up
def patch_root_urlconf():
    from django.conf.urls import include, patterns, url
    from django.core.urlresolvers import clear_url_caches, reverse, NoReverseMatch
    from django.utils.importlib import import_module

    try:
        reverse('tasks:execute')
    except NoReverseMatch:
        root = import_module(settings.ROOT_URLCONF)
        root.urlpatterns = patterns('', url(r'^tasks/', include('django_sae.contrib.tasks.urls', 'tasks',
                                                                'tasks')), ) + root.urlpatterns
        clear_url_caches() 
Example #22
Source File: generators.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def __init__(self, patterns=None, urlconf=None):
        if patterns is None:
            if urlconf is None:
                # Use the default Django URL conf
                urlconf = settings.ROOT_URLCONF

            # Load the given URLconf module
            if isinstance(urlconf, six.string_types):
                urls = import_module(urlconf)
            else:
                urls = urlconf
            patterns = urls.urlpatterns

        self.patterns = patterns 
Example #23
Source File: views.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, linter):
        super().__init__(linter)

        if 'DJANGO_SETTINGS_MODULE' in os.environ:
            django.setup()

            project_urls = import_module(settings.ROOT_URLCONF)
            project_urls = project_urls.urlpatterns
        else:
            project_urls = []
        self.views_by_module = self._url_view_mapping(project_urls)
        self.view_module = None 
Example #24
Source File: test_misc.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def reload_urlconf():
    """
    Reload url conf

    Make sure to use clear_url_caches along with this
    """
    if dj_settings.ROOT_URLCONF in sys.modules:
        conf = reload(sys.modules[dj_settings.ROOT_URLCONF])
    else:
        from inboxen import urls as conf

    return conf 
Example #25
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_missing_root_urlconf(self):
        # Removing ROOT_URLCONF is safe, as override_settings will restore
        # the previously defined settings.
        del settings.ROOT_URLCONF
        with self.assertRaises(AttributeError):
            self.client.get("/middleware_exceptions/view/") 
Example #26
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_urls_exception(self):
        """
        URLResolver should raise an exception when no urlpatterns exist.
        """
        resolver = URLResolver(RegexPattern(r'^$'), settings.ROOT_URLCONF)

        with self.assertRaisesMessage(
            ImproperlyConfigured,
            "The included URLconf 'urlpatterns_reverse.no_urls' does not "
            "appear to have any patterns in it. If you see valid patterns in "
            "the file then the issue is probably caused by a circular import."
        ):
            getattr(resolver, 'url_patterns') 
Example #27
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_missing_root_urlconf(self):
        # Removing ROOT_URLCONF is safe, as override_settings will restore
        # the previously defined settings.
        del settings.ROOT_URLCONF
        with self.assertRaises(AttributeError):
            self.client.get("/middleware_exceptions/view/") 
Example #28
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_urls_exception(self):
        """
        URLResolver should raise an exception when no urlpatterns exist.
        """
        resolver = URLResolver(RegexPattern(r'^$'), settings.ROOT_URLCONF)

        with self.assertRaisesMessage(
            ImproperlyConfigured,
            "The included URLconf 'urlpatterns_reverse.no_urls' does not "
            "appear to have any patterns in it. If you see valid patterns in "
            "the file then the issue is probably caused by a circular import."
        ):
            getattr(resolver, 'url_patterns') 
Example #29
Source File: helpers.py    From avos with Apache License 2.0 5 votes vote down vote up
def _reload_urls(self):
        """CLeans up URLs.

        Clears out the URL caches, reloads the root urls module, and
        re-triggers the autodiscovery mechanism for Horizon. Allows URLs
        to be re-calculated after registering new dashboards. Useful
        only for testing and should never be used on a live site.
        """
        urlresolvers.clear_url_caches()
        reload(import_module(settings.ROOT_URLCONF))
        base.Horizon._urls() 
Example #30
Source File: base.py    From avos with Apache License 2.0 5 votes vote down vote up
def _reload_urls(self):
        """Clears out the URL caches, reloads the root urls module, and
        re-triggers the autodiscovery mechanism for Horizon. Allows URLs
        to be re-calculated after registering new dashboards. Useful
        only for testing and should never be used on a live site.
        """
        urlresolvers.clear_url_caches()
        reload(import_module(settings.ROOT_URLCONF))
        base.Horizon._urls()