我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用django.core.urlresolvers.RegexURLResolver()。
def find_url_callbacks(urls_module): if isinstance(urls_module, list): urlpatterns = urls_module hid_list = [] else: urlpatterns = urls_module.urlpatterns hid_list = [urls_module.__name__] for pattern in urlpatterns: if isinstance(pattern, RegexURLPattern): hid_list.append(pattern.callback.__module__) elif isinstance(pattern, RegexURLResolver): hid_list += find_url_callbacks(pattern.urlconf_module) return hid_list # Add templatetags and context processors for each installed app.
def check_resolver(resolver): """ Recursively check the resolver. """ from django.core.urlresolvers import RegexURLPattern, RegexURLResolver warnings = [] for pattern in resolver.url_patterns: if isinstance(pattern, RegexURLResolver): warnings.extend(check_include_trailing_dollar(pattern)) # Check resolver recursively warnings.extend(check_resolver(pattern)) elif isinstance(pattern, RegexURLPattern): warnings.extend(check_pattern_name(pattern)) warnings.extend(check_pattern_startswith_slash(pattern)) return warnings
def decorate_url_pattern(self, pattern, *args, **kwargs): """Decorate a RegexURLPattern or RegexURLResolver. Args: resolve_fn: Either RegexURLPattern or RegexURLResolver, from django.core.urlresolvers This decorates the callback for a url after it gets resolved with self.decorate_method. """ resolve_fn = pattern.resolve @functools.wraps(resolve_fn) def patch_resolve(path): result = resolve_fn(path) if result: result.func = self.decorate_method( result.func, *args, **kwargs) return result pattern.resolve = patch_resolve return pattern
def subclass_view(self, request, path): """ Forward any request to a custom view of the real admin. """ ct_id = int(request.GET.get('ct_id', 0)) if not ct_id: # See if the path started with an ID. try: pos = path.find('/') if pos == -1: object_id = long(path) else: object_id = long(path[0:pos]) except ValueError: raise Http404("No ct_id parameter, unable to find admin subclass for path '{0}'.".format(path)) ct_id = self.model.objects.values_list('polymorphic_ctype_id', flat=True).get(pk=object_id) real_admin = self._get_real_admin_by_ct(ct_id) resolver = RegexURLResolver('^', real_admin.urls) resolvermatch = resolver.resolve(path) # May raise Resolver404 if not resolvermatch: raise Http404("No match for path '{0}' in admin subclass.".format(path)) return resolvermatch.func(request, *resolvermatch.args, **resolvermatch.kwargs)
def get_resolver(patterns=None): return RegexURLResolver(r'^/', patterns or redirectpatterns)
def __call__(self, fn, *args, **kwargs): """Delegate the decoration to the appropriate method.""" if isinstance(fn, functools.partial) and not hasattr(fn, '__module__'): raise ValueError( 'Cannot decorate a bare functools.partial view. ' 'You must invoke functools.update_wrapper(partial_view, ' 'full_view) first.') if not isinstance(fn, type) and isinstance(fn, collections.Callable): return self.decorate_method(fn, *args, **kwargs) elif isinstance(fn, tuple): # Must be an include('my_app.urls') we're decorating return self.decorate_include(fn, *args, **kwargs) elif isinstance(fn, (RegexURLPattern, RegexURLResolver)): return self.decorate_url_pattern(fn, *args, **kwargs) elif isinstance(fn, type) and issubclass(fn, BaseModelAdmin): if issubclass(fn, InlineModelAdmin): raise TypeError("Cannot decorate Inlines. See " "baya.admin.options.BayaInline instead.") return self.decorate_admin(fn, *args, **kwargs) elif isinstance(fn, six.string_types): raise TypeError("Cannot decorate string-path to view: %s." % fn) else: # You'll probably only get here if you're trying to decorate # a class-based view raise TypeError( "Invalid type for requires decorator (%s). " "You cannot decorate class-based views. Decorate " "the URL or the as_view method instead." % type(fn))
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('$').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
def test_returns_regex_url_resolver_if_passed_url_includes(self): url_includes = ( (Mock(), Mock(), Mock()), [Mock(), Mock(), Mock()], ) for includes in url_includes: resolver = simple_url('/home-page/', includes, sentinel.kwargs, sentinel.name) self.assertIsInstance(resolver, RegexURLResolver)
def get_views(urlpatterns, base=''): views = OrderedDict() for pattern in urlpatterns: if isinstance(pattern, RegexURLResolver): views.update(get_views( urlpatterns=pattern.url_patterns, base=base + pattern.regex.pattern, )) elif isinstance(pattern, RegexURLPattern): url = base + pattern.regex.pattern url = URL_PARAMETER_PATTERN.sub('{\g<param>}', simplify_regex(url)) views[url] = pattern.callback return views
def handle_message(self, message, bot_service): """ Process incoming message generating a response to the sender. :param message: Generic message received from provider :param bot_service: Service Integration :type bot_service: IntegrationBot :class:`IntegrationBot <permabots.models.bot.IntegrationBot>` .. note:: Message content will be extracted by IntegrationBot """ urlpatterns = [] state_context = {} chat_state = bot_service.get_chat_state(message) for handler in caching.get_or_set_related(self, 'handlers', 'response', 'request', 'target_state'): if handler.enabled: source_states = caching.get_or_set_related(handler, 'source_states') if chat_state: state_context = chat_state.ctx if not source_states or (chat_state and chat_state.state in source_states): urlpatterns.append(handler.urlpattern()) resolver = RegexURLResolver(r'^', urlpatterns) try: resolver_match = resolver.resolve(bot_service.message_text(message)) except Resolver404: logger.warning("Handler not found for %s" % message) else: callback, callback_args, callback_kwargs = resolver_match logger.debug("Calling callback:%s for message %s with %s" % (callback, message, callback_kwargs)) text, keyboard, target_state, context = callback(self, message=message, service=bot_service.identity, state_context=state_context, **callback_kwargs) if target_state: self.update_chat_state(bot_service, message, chat_state, target_state, context) keyboard = bot_service.build_keyboard(keyboard) bot_service.send_message(bot_service.get_chat_id(message), text, keyboard, message)
def __init__(self, conf): self.resolver = RegexURLResolver(r'^', conf)