def render_page_card(context, page): from maps.widgets import map_options_for_region cache = get_cache('long-living') request = context['request'] card = cache.get('card:%s,%s' % (get_urlconf() or settings.ROOT_URLCONF, page.id)) if card: return card _file, _map = None, None # Try and get a useful image _file = page.get_highlight_image() # Otherwise, try and get a map if not _file and hasattr(page, 'mapdata'): olwidget_options.update(map_options_for_region(page.region)) _map = InfoMap( [(page.mapdata.geom, '')], options=olwidget_options ).render(None, None, {'id': 'map_page_id_%s' % page.id}) card = render_to_string('cards/base.html', { 'obj': page, 'file': _file.file if _file else None, 'map': _map, 'title': page.name, 'content': page.content, }) cache.set('card:%s,%s' % (get_urlconf() or settings.ROOT_URLCONF, page.id), card) return card
def reset_urlresolvers_caches(self): # reset urlresolvers cache in order to update # urlpatterns provided by adminsite, to include # the just registered models if get_urlconf() is None: set_urlconf(settings.ROOT_URLCONF) reload_importlib_module(get_urlconf()) clear_url_caches()
def setUpClass(cls): cls.siteblocks = SiteBlocks() cls.b1 = Block(alias='main', url='*', contents='main_every_visible') cls.b1.save(force_insert=True) cls.b2 = Block(alias='main', description='hidden', url='*', contents='main_every_hidden', hidden=True) cls.b2.save(force_insert=True) cls.b3 = Block(alias='multiple', url='*', contents='multiple_1') cls.b3.save(force_insert=True) cls.b4 = Block(alias='multiple', url='*', contents='multiple_2') cls.b4.save(force_insert=True) cls.b5 = Block(alias='filtered_1', url='/news.*', contents='filtered_1_1') cls.b5.save(force_insert=True) cls.b6 = Block(alias='filtered_1', url='/gro{1,2}ves', contents='filtered_1_2') cls.b6.save(force_insert=True) cls.b7 = Block(alias='named_1', url=':named_url', contents='named_1_1') cls.b7.save(force_insert=True) cls.b8 = Block(alias='named_2', url=':namespaced:url', contents='named_2_1') cls.b8.save(force_insert=True) # set urlconf to one from test cls.old_urlconf = urlresolvers.get_urlconf() urlresolvers.set_urlconf('siteblocks.tests')
def alternate_languages(context): request = context['request'] is_lang = False lang_list = [] alternate = "" for lang in settings.LANGUAGES: lang_regex = ("/%s/") % lang[0] if lang_regex in request.path: is_lang = True else: lang_list.append(lang[0]) if hasattr(request, 'urlconf') and request.urlconf is not None: urlconf = request.urlconf else: urlconf = get_urlconf() locale, path = utils.strip_path(request.path_info) hostname = request.get_host().split(":")[0] if is_lang: for lang in lang_list: locale_path = utils.locale_path(path, lang, host=hostname, urlconf=urlconf) alternate += ('<link rel="alternate" hreflang="%s" href="http://%s%s" />\n') % (lang, hostname ,locale_path) return alternate
def mock_hosts_middleware(self, request): # This is certainly rather annoying, but needed because # we have to reload everything as we're changing settings # dynamically. import django_hosts reload(django_hosts) import main.hosts reload(main.hosts) import django_hosts.reverse reload(django_hosts.reverse) import django_hosts.middleware reload(django_hosts.middleware) from django_hosts.middleware import BaseHostsMiddleware current_urlconf = get_urlconf() or settings.ROOT_URLCONF middleware = BaseHostsMiddleware() host, kwargs = middleware.get_host(request.get_host()) request.urlconf = host.urlconf request.host = host set_urlconf(host.urlconf) # Annddd we also need to render the phased template response, too! Whew. yield set_urlconf(current_urlconf)
def get_form(self, request, obj=None, **kwargs): """Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself. """ if obj is not None and obj.parent is not None: self.previous_parent = obj.parent previous_parent_id = self.previous_parent.id else: previous_parent_id = None my_choice_field = TreeItemChoiceField(self.tree, initial=previous_parent_id) form = super(TreeItemAdmin, self).get_form(request, obj, **kwargs) my_choice_field.label = form.base_fields['parent'].label my_choice_field.help_text = form.base_fields['parent'].help_text # Replace 'parent' TreeItem field with new appropriate one form.base_fields['parent'] = my_choice_field # Try to resolve all currently registered url names including those in namespaces. if not getattr(self, 'known_url_names', False): self.known_url_names = [] self.known_url_rules = [] resolver = get_resolver(get_urlconf()) for ns, (url_prefix, ns_resolver) in resolver.namespace_dict.items(): if ns != 'admin': self._stack_known_urls(ns_resolver.reverse_dict, ns) self._stack_known_urls(resolver.reverse_dict) self.known_url_rules = sorted(self.known_url_rules) form.known_url_names_hint = _('You are seeing this warning because "URL as Pattern" option is active and pattern entered above seems to be invalid. Currently registered URL pattern names and parameters: ') form.known_url_names = self.known_url_names form.known_url_rules = self.known_url_rules return form
def _clear_frontpage(region): from pages.cache import varnish_invalidate_url from .views import FrontPageView current_urlconf = get_urlconf() or settings.ROOT_URLCONF region = region key = FrontPageView.get_cache_key(region=region.slug) cache.delete(key) if region.regionsettings.domain: # Has a domain, ugh. Need to clear two URLs on two hosts, in this case set_urlconf('main.urls_no_region') key = FrontPageView.get_cache_key(region=region.slug) cache.delete(key) varnish_invalidate_url(region.get_absolute_url(), hostname=region.regionsettings.domain) # Now invalidate main path on LocalWiki hub set_urlconf('main.urls') key = FrontPageView.get_cache_key(region=region.slug) cache.delete(key) varnish_invalidate_url(region.get_absolute_url()) else: key = FrontPageView.get_cache_key(region=region.slug) cache.delete(key) varnish_invalidate_url(region.get_absolute_url()) set_urlconf(current_urlconf)
def response_for_exception(request, exc): if isinstance(exc, Http404): if settings.DEBUG: response = debug.technical_404_response(request, exc) else: response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc) elif isinstance(exc, PermissionDenied): logger.warning( 'Forbidden (Permission denied): %s', request.path, extra={'status_code': 403, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc) elif isinstance(exc, MultiPartParserError): logger.warning( 'Bad request (Unable to parse request body): %s', request.path, extra={'status_code': 400, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SuspiciousOperation): # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__) security_logger.error( force_text(exc), extra={'status_code': 400, 'request': request}, ) if settings.DEBUG: response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) else: response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SystemExit): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise else: signals.got_request_exception.send(sender=None, request=request) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) # Force a TemplateResponse to be rendered. if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)): response = response.render() return response
def get_cache_key(*args, **kwargs): from django.core.urlresolvers import get_urlconf from pages.models import name_to_url urlconf = get_urlconf() or settings.ROOT_URLCONF region = CacheMixin.get_region_slug_param(*args, **kwargs) # Control characters and whitespace not allowed in memcached keys return 'map:%s/%s/main_map' % (urlconf, name_to_url(region))
def render(self, context): from django.core.urlresolvers import get_urlconf, get_resolver resolver = get_resolver(get_urlconf()) jsurl = '/' if self.url in resolver.reverse_dict: url = resolver.reverse_dict[self.url][0][0][0] jsurl = re.sub(re.compile('\%(\(\w+\))\w'), '%s', url) return "/%(url)s" % { 'url': jsurl }
def get_cache_key(*args, **kwargs): from django.core.urlresolvers import get_urlconf from pages.models import name_to_url urlconf = get_urlconf() or settings.ROOT_URLCONF slug = kwargs.get('slug') region = CacheMixin.get_region_slug_param(*args, **kwargs) # Control characters and whitespace not allowed in memcached keys return '%s/%s/%s' % (urlconf, name_to_url(region), slugify(slug).replace(' ', '_'))
def get_form(self, request, obj=None, **kwargs): """Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself. """ class TreeItemChoiceField(ChoiceField): """We use custom ChoiceField as to have a chance to resolve TreeItem by ID from dropdown. """ def clean(self, value): if value == '': return None return TreeItem.objects.get(pk=value) # We build choices dropdown using 'sitetree_tree' tag tree_token = u'sitetree_tree from "%s" template "admin/sitetree/tree/tree_combo.html"' % self.tree.alias my_context = template.RequestContext(request, current_app='admin') choices_str = sitetree_tree(template.Parser(None), template.Token(token_type=template.TOKEN_BLOCK, contents=tree_token)).render(my_context) tree_choices = [('', '---------')] for line in choices_str.splitlines(): if line.strip() != '': splitted = line.split(':::') tree_choices.append((splitted[0], mark_safe(splitted[1]))) if obj is not None and obj.parent is not None: self.previous_parent = obj.parent previous_parent_id = self.previous_parent.id else: previous_parent_id = None my_choice_field = TreeItemChoiceField(choices=tree_choices, initial=previous_parent_id) form = super(TreeItemAdmin, self).get_form(request, obj, **kwargs) my_choice_field.label = form.base_fields['parent'].label my_choice_field.help_text = form.base_fields['parent'].help_text # Replace 'parent' TreeItem field with new appropriate one form.base_fields['parent'] = my_choice_field # Try to resolve all currently registered url names. if not getattr(self, 'known_url_names', False): self.known_url_names = [] self.known_url_rules = [] reverse_dict = get_resolver(get_urlconf()).reverse_dict for url_name, url_rules in reverse_dict.items(): if isinstance(url_name, basestring): self.known_url_names.append(url_name) self.known_url_rules.append('<b>%s</b> %s' % (url_name, ' '.join(url_rules[0][0][1]))) self.known_url_rules = sorted(self.known_url_rules) form.known_url_names_hint = _('You are seeing this warning because "URL as Pattern" option is active and pattern entered above seems to be invalid. Currently registered URL pattern names and parameters: ') form.known_url_names = self.known_url_names form.known_url_rules = self.known_url_rules return form
def populate_menu(name): global _menu_lookups if name in _menu_lookups: return _menu_lookups[name] else: urlconf = get_urlconf() r = get_resolver(urlconf) _menu_lookups[name] = _populate_menu(r,name) return _menu_lookups[name]
def setUpClass(cls): cls.sitetree = SiteTree() t1 = Tree(alias='tree1') t1.save(force_insert=True) t1_root = TreeItem(title='root', tree=t1, url='/') t1_root.save(force_insert=True) t1_root_child1 = TreeItem(title='child1', tree=t1, parent=t1_root, url='/about/') t1_root_child1.save(force_insert=True) t1_root_child2 = TreeItem(title='child2', tree=t1, parent=t1_root, url='articles_list', urlaspattern=True) t1_root_child2.save(force_insert=True) t1_root_child2_sub1 = TreeItem(title='subchild1', tree=t1, parent=t1_root_child2, url='articles_detailed art_id', urlaspattern=True) t1_root_child2_sub1.save(force_insert=True) t1_root_child2_sub2 = TreeItem(title='subchild2', tree=t1, parent=t1_root_child2, url='/not_articles/10/') t1_root_child2_sub2.save(force_insert=True) t1_root_child3 = TreeItem(title='child_with_var_str', tree=t1, parent=t1_root, url='somevar_str', urlaspattern=True) t1_root_child3.save(force_insert=True) t1_root_child4 = TreeItem(title='child_with_var_list', tree=t1, parent=t1_root, url='somevar_list', urlaspattern=True) t1_root_child4.save(force_insert=True) t2 = Tree(alias='tree2') t2.save(force_insert=True) t2_root1 = TreeItem(title='{{ t2_root1_title }}', tree=t2, url='/') t2_root1.save(force_insert=True) t2_root2 = TreeItem(title='put {{ t2_root2_title }} inside', tree=t2, url='/sub/') t2_root2.save(force_insert=True) t2_root3 = TreeItem(title='for logged in only', tree=t2, url='/some/', access_loggedin=True) t2_root3.save(force_insert=True) cls.t1 = t1 cls.t1_root = t1_root cls.t1_root_child1 = t1_root_child1 cls.t1_root_child2 = t1_root_child2 cls.t1_root_child3 = t1_root_child3 cls.t1_root_child2_sub1 = t1_root_child2_sub1 cls.t1_root_child2_sub2 = t1_root_child2_sub2 cls.t2 = t2 cls.t2_root1 = t2_root1 cls.t2_root2 = t2_root2 cls.t2_root3 = t2_root3 # set urlconf to test's one cls.old_urlconf = urlresolvers.get_urlconf() urlresolvers.set_urlconf('sitetree.tests')
def test_request_urlconf_string(self): request = rf.get('/') set_urlconf('tests.urls') middleware = DebugToolbarMiddleware() middleware.process_request(request) patterns = get_resolver(get_urlconf()).url_patterns self.assertTrue(hasattr(patterns[1], '_callback_str')) self.assertEqual(patterns[-1]._callback_str, 'tests.views.execute_sql')
def get_url_for_share(self, request): # Want to use a semi-canonical URL here if request.host.name == settings.DEFAULT_HOST: return self.get_absolute_url() else: current_urlconf = get_urlconf() or settings.ROOT_URLCONF set_urlconf(settings.ROOT_URLCONF) url = self.get_absolute_url() set_urlconf(current_urlconf) return url
def locale_url(path, locale='', host=None, prefix='', urlconf=None): """ Generate the localeurl-enabled URL from a path without locale prefix. If the locale is empty settings.LANGUAGE_CODE is used. """ if urlconf is None: urlconf = get_urlconf() path = locale_path(path, locale, host=host, urlconf=urlconf) return add_script_prefix(path, prefix=prefix)
def get_api(namespace): ''' Returns the root endpoint matching the namespace ''' from django.core.urlresolvers import get_resolver, get_urlconf #there should be a better way to do this... urlconf = get_urlconf() resolver = get_resolver(urlconf) result = resolver.namespace_dict[namespace] return result[1].urlconf_name
def urls_by_namespace(namespace, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): """ Return a dictionary containing the name together with the URL of all configured URLs specified for this namespace. """ warnings.warn("urls_by_namespace is deprecated. Please view django-angular documentation for new way to manage URLs", DeprecationWarning) if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} if prefix is None: prefix = get_script_prefix() if not namespace or not isinstance(namespace, six.string_types): raise AttributeError('Attribute namespace must be of type string') path = namespace.split(':') path.reverse() resolved_path = [] ns_pattern = '' while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, # use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: if resolved_path: raise NoReverseMatch("%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) resolver = get_ns_resolver(ns_pattern, resolver) return dict((name, iri_to_uri(resolver._reverse_with_prefix(name, prefix, *args, **kwargs))) for name in resolver.reverse_dict.keys() if isinstance(name, six.string_types))
def get_resolve(path, urlconf=None): if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) app_list = resolver.app_dict resolve = resolver.resolve(path) resolve.app_list = app_list return resolve
def create_rules(urlconf=None): """ Creates rules from conf """ if urlconf is None: urlconf = get_urlconf() root_resolver = get_resolver(urlconf) rule_list = create_rule_list(root_resolver, '') return u'\n'.join(rule_list)
def setUpClass(cls): super(BlogPageTests, cls).setUpClass() User = get_user_model() Site.objects.get_or_create(id=settings.SITE_ID, defaults=dict(domain='django.localhost', name='django at localhost')) cls.user = User.objects.create_superuser("fluent-blogs-admin", '*****@*****.**', 'admin') # Testing with other URLconf, this works for every Django version cls._old_urlconf = get_urlconf() set_urlconf('fluent_blogs.pagetypes.blogpage.tests.urls')
def get_site_dict(app_name='filebrowser'): """ Return a dict with all *deployed* FileBrowser sites that have a given app_name. """ if not _sites_cache.has_key(app_name): return {} # Get names of all deployed filebrowser sites with a give app_name deployed = get_resolver(get_urlconf()).app_dict[app_name] # Get the deployed subset from the cache return dict((k,v) for k, v in _sites_cache[app_name].iteritems() if k in deployed)
def page(context, album_name, album_url, page_number): if get_urlconf() == 'webxiang.urls_static': if page_number > 1: # Translators: this is an URL return _('page-%(number)s.html') % {'number': page_number} else: return 'index.html' else: if page_number > 1: return '?page=%s' % page_number else: return album_url
def test_restore_urlconf_after_request(self): """ The urlconf attribute for the current thread should remain intact after each request, When is set to None it means 'use default from settings'. """ set_urlconf(None) urlconf = get_urlconf() self.assertIsNone(urlconf) self.client.get(self.url, HTTP_HOST='pip.readthedocs.org') urlconf = get_urlconf() self.assertIsNone(urlconf) self.client.get(self.url) urlconf = get_urlconf() self.assertIsNone(urlconf) self.client.get(self.url, HTTP_HOST='pip.readthedocs.org') urlconf = get_urlconf() self.assertIsNone(urlconf)
def process_request(self, request): # Find best match, falling back to settings.DEFAULT_HOST host, kwargs = self.get_host(request.get_host()) request.urlconf = host.urlconf request.host = host try: current_urlconf = get_urlconf() set_urlconf(host.urlconf) return host.callback(request, **kwargs) finally: # Reset URLconf for this thread on the way out for complete # isolation of request.urlconf set_urlconf(current_urlconf)
def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} prefix = kwargs.get('prefix') or None urlconf = kwargs.get('urlconf') or None if urlconf is None: urlconf = get_urlconf() locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) stipped_prefix, path = utils.strip_script_prefix(url, prefix = prefix) return utils.locale_url(path, locale, prefix = prefix, urlconf=urlconf)
def get_cache_key(*args, **kwargs): from django.core.urlresolvers import get_urlconf from pages.models import name_to_url import urllib urlconf = get_urlconf() or settings.ROOT_URLCONF region = CacheMixin.get_region_slug_param(*args, **kwargs) slug = kwargs.get('slug') # Control characters and whitespace not allowed in memcached keys date1 = name_to_url(kwargs.get('date1', '')) date2 = name_to_url(kwargs.get('date2', '')) version1 = name_to_url(kwargs.get('version1', '')) version2 = name_to_url(kwargs.get('version2', '')) return 'diff:%s/%s/%s/%s/%s/%s/%s' % (urlconf, name_to_url(region), date1, date2, version1, version2, slugify(slug).replace(' ', '_'))
def process_exception(self, request, exception): # don't process 404s if isinstance(exception, Http404): return info = self._collect_exception_info(request, exception) # send via celery ErrorPanel.queue_event(info) # return 500 response the same way django would callback, param_dict = get_resolver(get_urlconf()).resolve500() return callback(request, **param_dict)
def endpoint_string_pattern(viewname, with_host=False, pattern_subdomain='www', force_secure=False): urlconf = get_urlconf() resolver = get_resolver(urlconf) args = resolver.reverse_dict[viewname][0][0][1][:] pattern = resolver.reverse_dict[viewname][0][0][0] prefix = get_script_prefix() prefix_norm, prefix_args = normalize(urlquote(prefix))[0] candidate_pat = prefix_norm.replace('%', '%%') + pattern pattern_args = {arg: '{%s}' % arg for arg in args} path = candidate_pat % pattern_args if with_host: return '%s//%s.%s%s' % (('https:' if force_secure else ''), pattern_subdomain, settings.TOP_DOMAIN, path) return path
def replace_urls(patterns, extra=None): """ Context manager to replace the root URLconf with a list of URLpatterns in-memory. This is admittedly somewhat black-magicky. :param patterns: List of URLpatterns :type patterns: list[RegexURLResolver] :param extra: Dict to add to the created urlconf :type extra: dict """ old_urlconf = get_urlconf(default=django.conf.settings.ROOT_URLCONF) urlconf_module_name = "replace_urls_%s" % uuid.uuid4() module = types.ModuleType(urlconf_module_name) module.urlpatterns = patterns module.__dict__.update(extra or ()) sys.modules[urlconf_module_name] = module set_urlconf(urlconf_module_name) clear_url_caches() with override_settings(ROOT_URLCONF=urlconf_module_name): yield set_urlconf(old_urlconf) clear_url_caches() sys.modules.pop(urlconf_module_name)
response = self.c.login(username='******', password='******') self.assertTrue(response) # Execute tests test_browse(self) test_createdir(self) test_upload(self) test_do_upload(self) test_detail(self) test_delete_confirm(self) test_delete(self) ### CREATION OF TEST CASES # Get the names of all deployed filebrowser sites with the given all_sites = get_resolver(get_urlconf()).app_dict[APP_NAME] this_module = sys.modules[__name__] ## Create a test class for each deployed filebrowser site for site in all_sites: print 'Creating Test for the FileBrowser site:', site # Create a subclass of TestCase testcase_class = type('TestSite_' + site, (TestCase, ), { 'site_name': site, 'c': Client(), 'tmpdirs': None }) # Add setUp, tearDown, and runTest methods setattr(testcase_class, 'setUp', MethodType(setUp, None, testcase_class)) setattr(testcase_class, 'tearDown',
def wild_reverse(viewname, kwargs, urlconf=None, current_app=None): """ Returns the reverse url using as many of the given kwargs as possible. """ # copy/paste from django.core.urlresolvers.reverse if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) prefix = get_script_prefix() if not isinstance(viewname, six.string_types): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] if current_app: current_path = current_app.split(':') current_path.reverse() else: current_path = None resolved_path = [] ns_pattern = '' while path: ns = path.pop() current_ns = current_path.pop() if current_path else None # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_ns and current_ns in app_list: # If we are reversing for a particular app, # use that namespace ns = current_ns elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass if ns != current_ns: current_path = None try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) if ns_pattern: resolver = get_ns_resolver(ns_pattern, resolver) # /end copy/paste # this part adapted from # django.core.urlresolvers.RegexURLResolver._reverse_with_prefix text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()} if not resolver._populated: resolver._populate() original_lookup = lookup_view = view try: if resolver._is_callback(lookup_view): lookup_view = get_callable(lookup_view, True) except (ImportError, AttributeError) as e: raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e)) try: # note: this doesn't cover the possibility of multiple patterns returned params = resolver.reverse_dict[lookup_view][0][0][1] ok_kwargs = dict(((param, kwargs[param]) for param in params)) except KeyError: # this covers both statements above m = getattr(lookup_view, '__module__', None) n = getattr(lookup_view, '__name__', None) if m is not None and n is not None: lookup_view_s = "%s.%s" % (m, n) else: lookup_view_s = lookup_view raise NoReverseMatch("Reverse for '%s' with wild keyword arguments " "'%s' not found." % (lookup_view_s, kwargs)) # /end adaptation return force_text( iri_to_uri(resolver._reverse_with_prefix(view, prefix, **ok_kwargs)))
def setUpClass(cls): # set urlconf to test's one cls.urlconf_bak = urlresolvers.get_urlconf() urlresolvers.set_urlconf('sitegate.tests')
def refresh_urls(**kwargs): urlconf = get_urlconf() resolver = get_resolver(urlconf) refresh_resolver(resolver) clear_url_caches()
def get_cache_key(*args, **kwargs): from django.core.urlresolvers import get_urlconf urlconf = get_urlconf() or settings.ROOT_URLCONF region = CacheMixin.get_region_slug_param(*args, **kwargs) return '%s/%s/' % (urlconf, region)
def override_settings(ROOT_URLCONF=None): assert get_urlconf() == ROOT_URLCONF def dummy_dec(func): return func return dummy_dec
def urls_by_namespace(namespace, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): """ Return a dictionary containing the name together with the URL of all configured URLs specified for this namespace. """ if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} if prefix is None: prefix = get_script_prefix() if not namespace or not isinstance(namespace, six.string_types): raise AttributeError('Attribute namespace must be of type string') path = namespace.split(':') path.reverse() resolved_path = [] ns_pattern = '' while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, # use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) resolver = get_ns_resolver(ns_pattern, resolver) return dict( (name, iri_to_uri( resolver._reverse_with_prefix(name, prefix, *args, **kwargs))) for name in resolver.reverse_dict.keys() if (isinstance(name, six.string_types) and 'datasets-detail' not in name and 'swagger' not in name and 'organizations-detail' not in name and 'simple_api_test' not in name and 'data_files-mapping-suggestions' not in name))
def instalar_plugin(request): conteudo_arquivo = """aplicacoes = ( 'django.contrib.auth', 'third_party.grappelli', 'third_party.djblets', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.syndication', 'django.contrib.messages', 'modulos.catalogo', 'modulos.cinema', 'modulos.configuracao', 'modulos.disco_virtual', 'modulos.index_enquete', 'modulos.index_evento', 'modulos.index_gallery', 'modulos.newsletter', 'modulos.noticia', 'modulos.novidades', "modulos.onde_encontrar", 'modulos.paginas', 'modulos.popup', 'modulos.produtos', 'modulos.sociable', 'modulos.tags', 'modulos.scrum', 'third_party.debug_toolbar', 'third_party.tagging', )""" caminho_xml = "%s/../plugins_instalados.py" % settings.MEDIA_ROOT arquivo_xml = open(caminho_xml, "w") arquivo_xml.write(unicode(conteudo_arquivo).encode('utf-8')) arquivo_xml.close() return HttpResponse("Instalado") app = load_app("modulos.noticia") admin_teste = import_module("modulos.noticia.admin") connection = connections["default"] cursor = connection.cursor() style = color.no_style() sql_tabelas = sql.sql_create(app, style, connection) # for sql_query in sql_tabelas: # cursor.execute(sql_query) varaveis = import_module(get_urlconf()) reload(import_module(settings.ROOT_URLCONF)) clear_url_caches() #varaveis.urlpatterns = patterns('', #(r'^admin/configuracao/', include('modulos.configuracao.admin_urls')), #(r'^admin/index_enquete/', include('modulos.index_enquete.admin_urls')), #(r'^admin/', include(admin.site.urls)), #(r'^disco_virtual/', include('modulos.disco_virtual.urls')), #(r'^onde-encontrar/', include('modulos.onde_encontrar.urls')), #(r'^enquete/', include('modulos.index_enquete.urls')), #(r'^eventos/', include('modulos.index_evento.urls')), #(r'^galerias/', include('modulos.index_gallery.urls')), #(r'^grappelli/', include('grappelli.urls')), #(r'^newsletter/', include('modulos.newsletter.urls')), #(r'^popup/', include('modulos.popup.urls')), #(r'^noticia/', include('modulos.noticia.urls')), #(r'^utils/', include('modulos.utils.urls')), #(r'^site_media/(.*)', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), #) return HttpResponse("Instalado")
url(r'delete/$', delete, name='delete'), ] class MySyteUrlConf: urlpatterns = [ url(r'^$', index, name='index'), url(r'^login/$', auth, kwargs={'action': 'login'}, name='login'), url(r'^logout/$', auth, kwargs={'action': 'logout'}, name='logout'), url(r'^groups/', include(GroupConf('groups'), namespace='groups')), url(r'^users/', include(GroupConf('users'), namespace='users')), ] print('meu Root', settings.ROOT_URLCONF) print('get_urlconf', get_urlconf()) print('set_urlconf', MySyteUrlConf) set_urlconf(MySyteUrlConf) print('get_urlconf', get_urlconf()) print() print('Resolve:') print(resolve('/')) print(resolve('/login/')) print(resolve('/logout/')) print(resolve('/groups/')) print(resolve('/groups/1/')) print(resolve('/groups/new/')) print(resolve('/groups/delete/')) print(resolve('/users/'))
def view_from_url(named_url): # noqa """ Finds and returns the view class from a named url """ # code below is `stolen` from django's reverse method resolver = urlresolvers.get_resolver(urlresolvers.get_urlconf()) if type(named_url) in (list, tuple): named_url = named_url[0] parts = named_url.split(':') parts.reverse() view = parts[0] path = parts[1:] current_path = None resolved_path = [] ns_pattern = '' while path: ns = path.pop() current_ns = current_path.pop() if current_path else None # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_ns and current_ns in app_list: # If we are reversing for a particular app, # use that namespace ns = current_ns elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass if ns != current_ns: current_path = None try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) if ns_pattern: resolver = urlresolvers.get_ns_resolver(ns_pattern, resolver) # custom code, get view from reverse_dict reverse_dict = resolver.reverse_dict.dict() for key, url_obj in reverse_dict.items(): if url_obj == reverse_dict[view] \ and key != view: module = importlib.import_module(key.__module__) return getattr(module, key.__name__)
def render_canonical_url(context, obj=None): """ Returns the canonical URL associated with either the current request path or the provided object. """ # A non-request view of some sort if not 'request' in context: return '' if not 'region' in context: return '' request = context['request'] region = context['region'] if obj: if request.host.name == settings.DEFAULT_HOST: url = obj.get_absolute_url() if urllib.unquote(url) == request.path and not request.GET.keys(): # Don't bother rendering a canonical URL tag. return '' else: return '<link rel="canonical" href="%s" />' % url else: current_urlconf = get_urlconf() or settings.ROOT_URLCONF set_urlconf(settings.ROOT_URLCONF) url = obj.get_absolute_url() set_urlconf(current_urlconf) url = '%s%s%s' % (HOST_SCHEME, settings.MAIN_HOSTNAME, url) return '<link rel="canonical" href="%s" />' % url else: url = request.path if request.host.name == settings.DEFAULT_HOST: # We're on the default host, so let's not bother # rendering a canonical URL tag. return '' else: # We're on a custom domain, so let's render a URL # that points to the main host, but on the same # view, args, and kwargs. current_urlconf = get_urlconf() or settings.ROOT_URLCONF resolved = resolve(request.path) view_name, args, kwargs = resolved.view_name, resolved.args, resolved.kwargs set_urlconf(settings.ROOT_URLCONF) if 'region' not in kwargs or kwargs['region'] is None: kwargs['region'] = region.slug # Remove empty kwargs kwargs = {k: v for k, v in kwargs.iteritems() if v is not None} url = reverse(view_name, args=args, kwargs=kwargs) set_urlconf(current_urlconf) if request.META['QUERY_STRING']: qs = '?%s' % request.META['QUERY_STRING'] else: qs = '' url = '%s%s%s%s' % (HOST_SCHEME, settings.MAIN_HOSTNAME, url, qs) return '<link rel="canonical" href="%s" />' % url
def setUpClass(cls): cls.sitetree = SiteTree() t1 = Tree(alias='tree1') t1.save(force_insert=True) t1_root = TreeItem(title='root', tree=t1, url='/') t1_root.save(force_insert=True) t1_root_child1 = TreeItem(title='child1', tree=t1, parent=t1_root, url='/about/') t1_root_child1.save(force_insert=True) t1_root_child2 = TreeItem(title='child2', tree=t1, parent=t1_root, url='articles_list', urlaspattern=True, description='items_descr') t1_root_child2.save(force_insert=True) t1_root_child2_sub1 = TreeItem(title='subchild1', tree=t1, parent=t1_root_child2, url='articles_detailed art_id', urlaspattern=True) t1_root_child2_sub1.save(force_insert=True) t1_root_child2_sub2 = TreeItem(title='subchild2', tree=t1, parent=t1_root_child2, url='/not_articles/10/') t1_root_child2_sub2.save(force_insert=True) t1_root_child3 = TreeItem(title='child_with_var_str', tree=t1, parent=t1_root, url='somevar_str', urlaspattern=True) t1_root_child3.save(force_insert=True) t1_root_child4 = TreeItem(title='child_with_var_list', tree=t1, parent=t1_root, url='somevar_list', urlaspattern=True) t1_root_child4.save(force_insert=True) t2 = Tree(alias='tree2') t2.save(force_insert=True) t2_root1 = TreeItem(title='{{ t2_root1_title }}', tree=t2, url='/') t2_root1.save(force_insert=True) t2_root2 = TreeItem(title='put {{ t2_root2_title }} inside', tree=t2, url='/sub/') t2_root2.save(force_insert=True) t2_root3 = TreeItem(title='for logged in only', tree=t2, url='/some/', access_loggedin=True) t2_root3.save(force_insert=True) t2_root4 = TreeItem(title='url quoting', tree=t2, url='url 2 put_var', urlaspattern=True) t2_root4.save(force_insert=True) t2_root5 = TreeItem(title='url quoting 1.5 style', tree=t2, url="'url' 2 put_var", urlaspattern=True) t2_root5.save(force_insert=True) t2_root6 = TreeItem(title='url quoting 1.5 style', tree=t2, url='"url" 2 put_var', urlaspattern=True) t2_root6.save(force_insert=True) t2_root7 = TreeItem(title='for guests only', tree=t2, url='/some_other/', access_guest=True) t2_root7.save(force_insert=True) cls.t1 = t1 cls.t1_root = t1_root cls.t1_root_child1 = t1_root_child1 cls.t1_root_child2 = t1_root_child2 cls.t1_root_child3 = t1_root_child3 cls.t1_root_child2_sub1 = t1_root_child2_sub1 cls.t1_root_child2_sub2 = t1_root_child2_sub2 cls.t2 = t2 cls.t2_root1 = t2_root1 cls.t2_root2 = t2_root2 cls.t2_root3 = t2_root3 cls.t2_root4 = t2_root4 cls.t2_root5 = t2_root5 cls.t2_root6 = t2_root6 cls.t2_root7 = t2_root7 # set urlconf to test's one cls.old_urlconf = urlresolvers.get_urlconf() urlresolvers.set_urlconf('sitetree.tests')
def fuzzy_reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): """ from django/core/urlresolvers.py Unmodified reverse (just need to use our modified version of get_resolver) With the modified BRegexURLResolver retrieved through get_resolver this will not error when you pass in extra args (it assumes proper order and ignores trailing "extra" args) OR kwargs (it assumes you are passing at least the required keyworded arguments) It will still error if you pass both args AND kwargs at the same time. """ if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} if prefix is None: prefix = get_script_prefix() if not isinstance(viewname, basestring): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] resolved_path = [] ns_pattern = '' while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, # use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError, e: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (e, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % e) if ns_pattern: resolver = get_ns_resolver(ns_pattern, resolver)