本文整理匯總了Python中django.core.urlresolvers.Resolver404方法的典型用法代碼示例。如果您正苦於以下問題:Python urlresolvers.Resolver404方法的具體用法?Python urlresolvers.Resolver404怎麽用?Python urlresolvers.Resolver404使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.core.urlresolvers
的用法示例。
在下文中一共展示了urlresolvers.Resolver404方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: resolve
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def resolve(self, path):
path = force_text(path)
tried = []
match = self.regex.search(path)
if match:
new_path = path[match.end():]
for pattern in self.url_patterns:
try:
sub_match = pattern.resolve(new_path)
except Resolver404 as e:
sub_tried = e.args[0].get('tried')
if sub_tried is not None:
tried.extend([pattern] + t for t in sub_tried)
else:
tried.append([pattern])
else:
if sub_match:
sub_match_dict = dict(match.groupdict(), **self.default_kwargs)
sub_match_dict.update(sub_match.kwargs)
return ResolverMatch(self._decorate(sub_match.func), sub_match.args, sub_match_dict,
sub_match.url_name, self.app_name or sub_match.app_name,
[self.namespace] + sub_match.namespaces)
tried.append([pattern])
raise Resolver404({'tried': tried, 'path': new_path})
raise Resolver404({'path': path})
示例2: to_internal_value
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def to_internal_value(self, data):
try:
http_prefix = data.startswith(('http:', 'https:'))
except AttributeError:
self.fail('incorrect_type', data_type=type(data).__name__)
if http_prefix:
# If needed convert absolute URLs to relative path
data = urlparse(data).path
prefix = get_script_prefix()
if data.startswith(prefix):
data = '/' + data[len(prefix):]
try:
match = resolve(data)
except Resolver404:
self.fail('no_match')
try:
lookup_value = match.kwargs[self.lookup_url_kwarg]
lookup_kwargs = {self.lookup_field: lookup_value}
model = match.func.cls.model
return model.objects.get(**lookup_kwargs)
except (ObjectDoesNotExist, TypeError, ValueError):
self.fail('does_not_exist')
示例3: add_preserved_filters
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def add_preserved_filters(context, url, popup=False, to_field=None):
opts = context.get('opts')
preserved_filters = context.get('preserved_filters')
parsed_url = list(urlparse(url))
parsed_qs = dict(parse_qsl(parsed_url[4]))
merged_qs = dict()
if opts and preserved_filters:
preserved_filters = dict(parse_qsl(preserved_filters))
match_url = '/%s' % url.partition(get_script_prefix())[2]
try:
match = resolve(match_url)
except Resolver404:
pass
else:
current_url = '%s:%s' % (match.app_name, match.url_name)
changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
if changelist_url == current_url and '_changelist_filters' in preserved_filters:
preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))
merged_qs.update(preserved_filters)
if popup:
from django.contrib.admin.options import IS_POPUP_VAR
merged_qs[IS_POPUP_VAR] = 1
if to_field:
from django.contrib.admin.options import TO_FIELD_VAR
merged_qs[TO_FIELD_VAR] = to_field
merged_qs.update(parsed_qs)
parsed_url[4] = urlencode(merged_qs)
return urlunparse(parsed_url)
示例4: url_resolves
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def url_resolves(url):
try:
resolve(urlparse(url).path)
except Resolver404:
return False
return True
示例5: resolve
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def resolve(self, update):
try:
resolver_match = self.resolver.resolve(update.message.text)
return resolver_match
except Resolver404:
raise HandlerNotFound("No handler configured for %s" % update.message.text)
示例6: _should_log_route
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def _should_log_route(self, request):
# request.urlconf may be set by middleware or application level code.
# Use this urlconf if present or default to None.
# https://docs.djangoproject.com/en/2.1/topics/http/urls/#how-django-processes-a-request
# https://docs.djangoproject.com/en/2.1/ref/request-response/#attributes-set-by-middleware
urlconf = getattr(request, 'urlconf', None)
try:
route_match = resolve(request.path, urlconf=urlconf)
except Resolver404:
return False, None
method = request.method.lower()
view = route_match.func
func = view
# This is for "django rest framework"
if hasattr(view, 'cls'):
if hasattr(view, 'actions'):
actions = view.actions
method_name = actions.get(method)
if method_name:
func = getattr(view.cls, view.actions[method], None)
else:
func = getattr(view.cls, method, None)
elif hasattr(view, 'view_class'):
# This is for django class-based views
func = getattr(view.view_class, method, None)
no_logging = getattr(func, NO_LOGGING_ATTR, False)
no_logging_msg = getattr(func, NO_LOGGING_MSG_ATTR, None)
return no_logging, no_logging_msg
示例7: handle_message
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
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)
示例8: active_page
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def active_page(request, view_name):
from django.core.urlresolvers import resolve, Resolver404
if not request:
return ""
try:
return "active" if resolve(request.path_info).url_name == view_name else ""
except Resolver404:
return ""
示例9: get_url_resolver_match
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def get_url_resolver_match(self):
try:
return resolve(self.url)
except Resolver404:
self.set_error('Resource not found.', 404)
示例10: _is_real_url
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def _is_real_url(url):
"""
Users might have altered the URL parameters. Let's not just blindly
redirect; let's actually make sure we can get somewhere first.
"""
try:
resolve(url)
return True
except Resolver404:
return False
示例11: add_active_url_name
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def add_active_url_name(request):
"""Function to add active URL name to the page context"""
try:
resolved = resolve(request.path_info)
return {
'active_url_name': resolved.url_name,
'app_name': resolved.app_name
}
except Resolver404:
return {}
示例12: test_returns_nothing_with_error
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def test_returns_nothing_with_error(self, mock):
"""Test that when a resolve fails an empty context is returned"""
mock.side_effect = Resolver404()
context = add_active_url_name(self.request)
self.assertNotIn('active_url_name', context)
self.assertNotIn('app_name', context)
示例13: technical_404_response
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def technical_404_response(request, exception):
"Create a technical 404 error response. The exception should be the Http404."
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried # empty URLconf
or (request.path == '/'
and len(tried) == 1 # default URLconf
and len(tried[0]) == 1
and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
return default_urlconf(request)
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlconf = urlconf.__name__
caller = ''
try:
resolver_match = resolve(request.path)
except Resolver404:
pass
else:
obj = resolver_match.func
if hasattr(obj, '__name__'):
caller = obj.__name__
elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
caller = obj.__class__.__name__
if hasattr(obj, '__module__'):
module = obj.__module__
caller = '%s.%s' % (module, caller)
t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE)
c = Context({
'urlconf': urlconf,
'root_urlconf': settings.ROOT_URLCONF,
'request_path': error_url,
'urlpatterns': tried,
'reason': force_bytes(exception, errors='replace'),
'request': request,
'settings': get_safe_settings(),
'raising_view_name': caller,
})
return HttpResponseNotFound(t.render(c), content_type='text/html')
示例14: process_request
# 需要導入模塊: from django.core import urlresolvers [as 別名]
# 或者: from django.core.urlresolvers import Resolver404 [as 別名]
def process_request(self, request):
"""
Ignore unnecessary actions for static file requests, posts, or ajax
requests. We're only interested in redirecting following a 'natural'
request redirection to the `wagtailadmin_explore_root` or
`wagtailadmin_explore` views.
"""
referer_url = request.META.get('HTTP_REFERER')
return_to_index_url = request.session.get('return_to_index_url')
try:
if all((
return_to_index_url,
referer_url,
request.method == 'GET',
not request.is_ajax(),
resolve(request.path).url_name in ('wagtailadmin_explore_root',
'wagtailadmin_explore'),
)):
perform_redirection = False
referer_match = resolve(urlparse(referer_url).path)
if all((
referer_match.namespace == 'wagtailadmin_pages',
referer_match.url_name in (
'add',
'edit',
'delete',
'unpublish',
'copy'
),
)):
perform_redirection = True
elif all((
not referer_match.namespace,
referer_match.url_name in (
'wagtailadmin_pages_create',
'wagtailadmin_pages_edit',
'wagtailadmin_pages_delete',
'wagtailadmin_pages_unpublish'
),
)):
perform_redirection = True
if perform_redirection:
del request.session['return_to_index_url']
return HttpResponseRedirect(return_to_index_url)
except Resolver404:
pass
return None