我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用django.core.urlresolvers.get_script_prefix()。
def test_locale_url(self): previous_script_prefix = urlresolvers.get_script_prefix() urlresolvers.set_script_prefix("/blah/") self.assertEqual('/blah/en/about/localeurl/', utils.locale_url('/about/localeurl/')) self.assertEqual('/blah/en/about/localeurl/', utils.locale_url('/about/localeurl/', 'de')) self.assertEqual('/blah/en/about/localeurl/', utils.locale_url('/about/localeurl/', 'en')) self.assertEqual('/blah/en/about/localeurl/', utils.locale_url('/about/localeurl/', 'en-us')) self.assertEqual('/blah/nl-nl/about/localeurl/', utils.locale_url('/about/localeurl/', 'nl-nl')) self.assertEqual('/blah/test/independent/bla/bla', utils.locale_url('/test/independent/bla/bla', 'en')) urlresolvers.set_script_prefix(previous_script_prefix)
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix)-1:] try: view, args, kwargs = resolve(chomped_uri) except Resolver404: raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) bundle = self.build_bundle(request=request) return self.obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) # Data preparation.
def get_absolute_url(self): # Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
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)
def __init__(self, prefix): self.prefix = prefix self.old_prefix = get_script_prefix()
def test_redirect_with_script_prefix(self): previous_script_prefix = urlresolvers.get_script_prefix() urlresolvers.set_script_prefix('/prefix/') r1 = self.request_factory.get('/nl-be/test/independent/') r2 = self.middleware.process_request(r1) self.assertEqual(301, r2.status_code) self.assertEqual('/prefix/test/independent/', r2['Location']) # no infinite redirects r3 = self.request_factory.get('/test/independent/') r4 = self.middleware.process_request(r3) self.assertEqual(None, r4) urlresolvers.set_script_prefix(previous_script_prefix)
def strip_script_prefix(url): """ Strips the SCRIPT_PREFIX from the URL. Because this function is meant for use in templates, it assumes the URL starts with the prefix. """ assert url.startswith(urlresolvers.get_script_prefix()), \ "URL must start with SCRIPT_PREFIX: %s" % url pos = len(urlresolvers.get_script_prefix()) - 1 return url[:pos], url[pos:]
def add_script_prefix(path): """ Prepends the SCRIPT_PREFIX to a path. """ return ''.join([urlresolvers.get_script_prefix(), path[1:]])
def from_native(self, value): # Convert URL -> model instance pk # TODO: Use values_list queryset = self.queryset if queryset is None: raise Exception('Writable related fields must include a `queryset` argument') try: http_prefix = value.startswith(('http:', 'https:')) except AttributeError: msg = self.error_messages['incorrect_type'] raise ValidationError(msg % type(value).__name__) if http_prefix: # If needed convert absolute URLs to relative path value = urlparse.urlparse(value).path prefix = get_script_prefix() if value.startswith(prefix): value = '/' + value[len(prefix):] try: match = resolve(value) except Exception: raise ValidationError(self.error_messages['no_match']) if match.view_name != self.view_name: raise ValidationError(self.error_messages['incorrect_match']) try: return self.get_object(queryset, match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, TypeError, ValueError): raise ValidationError(self.error_messages['does_not_exist'])
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix)-1:] try: view, args, kwargs = resolve(chomped_uri) resource_name = kwargs['resource_name'] resource_class = self.resource_mapping[resource_name] except (Resolver404, KeyError): raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) parent_resource = resource_class(api_name=self._meta.api_name) kwargs = parent_resource.remove_api_resource_names(kwargs) bundle = Bundle(request=request) return parent_resource.obj_get(bundle, **kwargs)
def to_internal_value(self, data): """ TODO - I've had to copy this method from HyperlinkedRelatedField purely so that it can deal with polymorphic models. This probably is not ideal. """ 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.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') if self._serializer_is_polymorphic: # TODO - This is not really what we want. Need to make sure # that match.view_name points to a view which uses a subtype # serializer for this polymorphic serializer self.view_name = match.view_name if match.view_name != self.view_name: self.fail('incorrect_match') try: return self.get_object(match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, TypeError, ValueError): self.fail('does_not_exist')
def get_breadcrumbs(url, request=None): """ Given a url returns a list of breadcrumbs, which are each a tuple of (name, url). """ from rest_framework.reverse import preserve_builtin_query_params from rest_framework.settings import api_settings from rest_framework.views import APIView view_name_func = api_settings.VIEW_NAME_FUNCTION def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen): """ Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url. """ try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, # and if so add it to the breadcrumbs cls = getattr(view, 'cls', None) if cls is not None and issubclass(cls, APIView): # Don't list the same view twice in a row. # Probably an optional trailing slash. if not seen or seen[-1] != view: suffix = getattr(view, 'suffix', None) name = view_name_func(cls, suffix) insert_url = preserve_builtin_query_params(prefix + url, request) breadcrumbs_list.insert(0, (name, insert_url)) seen.append(view) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to # resolve more breadcrumbs url = url.rstrip('/') return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen) # Drop trailing non-slash off the end and continue to try to # resolve more breadcrumbs url = url[:url.rfind('/') + 1] return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen) prefix = get_script_prefix().rstrip('/') url = url[len(prefix):] return breadcrumbs_recursive(url, [], prefix, [])