我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.urls.resolve()。
def get_node_route_for_app_model(request, node, route_data): # Set name and component of the route. route_data['component'] = node.attr.get('component') route_data['name'] = node.attr.get('vue_js_router_name') # Add the link to fetch the data from the API. route_data['api']['fetch'] = { 'url': node.attr.get('fetch_url'), 'cache': bool(node.attr['cache']) if 'cache' in node.attr.keys() else True } request_url_name = resolve(request.path).url_name node_url_name = resolve(node.get_absolute_url()).url_name is_selected_node = request.path == node.get_absolute_url() or request_url_name == node_url_name if is_selected_node: # We need to prepare the initial structure of the fetched data. The actual data is added by the view. route_data['api']['fetched'] = { 'response': { 'data': {} } } route_data['params'] = node.attr.get('url_params', {}) route_data['path'] = node.get_absolute_url() return route_data
def test_simple_semester(): simple_url = reverse( 'semesterpage-semester', args=['fysmat', '1'], ) assert simple_url == '/fysmat/1/' resolver = resolve('/fysmat/1/') assert resolver.view_name == 'semesterpage-semester' assert resolver.func.__name__ == 'semester_view' kwargs = { 'study_program': 'fysmat', 'semester_number': '1', } assert resolver.kwargs == kwargs simple_semester = SemesterFactory.build( main_profile=None, study_program__slug='fysmat', ) assert simple_semester.get_absolute_url() == '/fysmat/1/'
def test_study_program(): study_program_url = reverse( 'semesterpage-studyprogram', args=['fysmat'], ) assert study_program_url == '/fysmat/' resolver = resolve('/fysmat/') assert resolver.view_name == 'semesterpage-studyprogram' assert resolver.func.__name__ == 'semester_view' kwargs = { 'study_program': 'fysmat', } assert resolver.kwargs == kwargs study_program = StudyProgramFactory.build( slug='fysmat', ) assert study_program.get_absolute_url() == '/fysmat/'
def test_main_profile(): main_profile_url = reverse( 'semesterpage-mainprofile', args=['fysmat', 'inmat'], ) assert main_profile_url == '/fysmat/inmat/' resolver = resolve('/fysmat/inmat/') assert resolver.view_name == 'semesterpage-mainprofile' assert resolver.func.__name__ == 'semester_view' kwargs = { 'study_program': 'fysmat', 'main_profile': 'inmat', } assert resolver.kwargs == kwargs main_profile = MainProfileFactory.build( slug='inmat', study_program__slug='fysmat', ) assert main_profile.get_absolute_url() == '/fysmat/inmat/'
def test_semester(): semester_url = reverse( 'semesterpage-semester', args=['fysmat', 'inmat', '1'], ) assert semester_url == '/fysmat/inmat/1/' resolver = resolve('/fysmat/inmat/1/') assert resolver.view_name == 'semesterpage-semester' assert resolver.func.__name__ == 'semester_view' kwargs = { 'study_program': 'fysmat', 'main_profile': 'inmat', 'semester_number': '1', } assert resolver.kwargs == kwargs semester = SemesterFactory.build( number=1, main_profile__slug='inmat', study_program__slug='fysmat', ) assert semester.get_absolute_url() == '/fysmat/inmat/1/'
def test_studentpage(): options_url = reverse( 'semesterpage-studyprogram', args=['olan'], ) assert options_url == '/olan/' resolver = resolve('/olan/') assert resolver.view_name == 'semesterpage-studyprogram' assert resolver.func.__name__ == 'semester_view' kwargs = { 'study_program': 'olan' } assert resolver.kwargs == kwargs options = OptionsFactory.build( user__username='olan', ) assert options.get_absolute_url() == '/olan/'
def test_new_thread_generates_subscription(self): forum = Forum.objects.all()[0] path = reverse('new-thread', kwargs={'forum_id': forum.pk}) response = self.scrub_client.post( path, { 'title': 'SAT is a lie', 'content': 'NP erect lol', 'forum': forum.pk }) match = resolve(response['Location']) thread = Thread.objects.get(pk=match.kwargs['thread_id']) subscription = ThreadFlag.objects.get(poster=self.scrub, thread=thread) self.assertTrue(subscription.subscribed)
def test_view_url_reversing(self): """Test view URL reversing""" assert str(self.url) == '/' assert ( resolve(self.url)._func_path == 'redirects.views.RedirectFormView' )
def test_view_url_reversing(self, redirect): """Test view URL reversing""" url = '/' + redirect.local_path resolver = resolve(url) assert resolver.view_name == 'redirects:redirect' assert resolver.kwargs == { 'local_path': redirect.local_path, } assert ( resolver._func_path == 'redirects.views.ActualRedirectView' )
def test_url_resolves_to_login_view(self): # login view? ?? url? ???? ??? # resolve??? ??? ?? URL? ???? view? ?? found = resolve(self.VIEW_URL) # ?? view? ???? ?? (.func??)? views.login??? ??? ?? self.assertEqual(found.func, views.login)
def test_url_resolves_to_change_profile_image_view(self): make_user_and_login(self.client) found = resolve('/member/profile/change-profile-image/') self.assertEqual(found.func, views.change_profile_image)
def __call__(self, request): url = resolve(request.path_info) if request.user.is_anonymous and url.url_name not in self.UNAUTHENTICATED_URLS: return redirect(reverse('common:login') + f'?next={request.path}') return self.get_response(request)
def byro_information(request): ctx = {'config': Configuration.get_solo()} try: ctx['url_name'] = resolve(request.path_info).url_name except Http404: ctx['url_name'] = '' if settings.DEBUG: ctx['development_warning'] = True with suppress(Exception): import subprocess ctx['byro_version'] = subprocess.check_output(['git', 'describe', '--always']) return ctx
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 clean(self): if "checks" in self.errors: del self.errors["checks"] self.cleaned_data["checks"] = None if "user" in self.errors: del self.errors["user"] self.cleaned_data["user"] = self.request_user if self.errors: return pootle_path = self.cleaned_data.get("path") path_keys = [ "project_code", "language_code", "dir_path", "filename"] try: path_kwargs = { k: v for k, v in resolve(pootle_path).kwargs.items() if k in path_keys} except Resolver404: raise forms.ValidationError('Unrecognised path') self.cleaned_data.update(path_kwargs) sort_on = "units" if "filter" in self.cleaned_data: unit_filter = self.cleaned_data["filter"] if unit_filter in ('suggestions', 'user-suggestions'): sort_on = 'suggestions' elif unit_filter in ('user-submissions', ): sort_on = 'submissions' sort_by_param = self.cleaned_data["sort"] self.cleaned_data["sort_by"] = ALLOWED_SORTS[sort_on].get(sort_by_param) self.cleaned_data["sort_on"] = sort_on
def test_resolve_account_URLs(self): resolver = resolve('/accounts/login/') self.assertEqual(resolver.view_name, 'account_login') resolver = resolve('/accounts/signup/') self.assertEqual(resolver.view_name, 'account_signup') resolver = resolve('/accounts/logout/') self.assertEqual(resolver.view_name, 'account_logout') resolver = resolve('/accounts/password/reset/') self.assertEqual(resolver.view_name, 'account_reset_password')
def url(self): url = self.get('ic-current-url', None) match = None if url is not None: url = url.strip() url = urlparse(url) if url.path: try: match = resolve(url.path) except Resolver404: pass return UrlMatch(url, match)
def forced_auth_req(self, method, url, user=None, data=None, request_format='json', **kwargs): """ Function that allows api methods to be called with forced authentication :param method: the HTTP method 'get'/'post' :type method: str :param url: the relative url to the base domain :type url: st :param user: optional user if not authenticated as the current user :type user: django.contrib.auth.models.User :param data: any data that should be passed to the API view :type data: dict """ factory = APIRequestFactory() view_info = resolve(url) data = data or {} view = view_info.func req_to_call = getattr(factory, method) request = req_to_call(url, data, format=request_format, **kwargs) user = user or self.user force_authenticate(request, user=user) response = view(request, *view_info.args, **view_info.kwargs) if hasattr(response, 'render'): response.render() return response
def test_reading_home_view(self): "Should use the correct view." self.assertEqual(resolve('/reading/').func.__name__, views.ReadingHomeView.__name__)
def test_publicationseries_list_view(self): "Should use the correct view." self.assertEqual(resolve('/reading/series/').func.__name__, views.PublicationSeriesListView.__name__)
def test_publicationseries_detail_view(self): "Should use the correct view." PublicationSeriesFactory(title='My Series') self.assertEqual(resolve('/reading/series/my-series/').func.__name__, views.PublicationSeriesDetailView.__name__)
def test_publication_list_view(self): "Should use the correct view." self.assertEqual(resolve('/reading/publications/').func.__name__, views.PublicationListView.__name__)
def test_publication_list_periodical_view(self): "Should use the correct view." self.assertEqual( resolve('/reading/publications/periodicals/').func.__name__, views.PublicationListView.__name__)
def test_reading_year_archive_view(self): "Should use the correct view." ReadingFactory(end_date=('2017-02-15')) self.assertEqual(resolve('/reading/2017/').func.__name__, views.ReadingYearArchiveView.__name__)
def test_home_view(self): "Should use the correct view." self.assertEqual(resolve('/').func.__name__, views.HomeView.__name__)
def test_creator_list_view(self): "Should use the correct view." self.assertEqual(resolve('/creators/').func.__name__, views.CreatorListView.__name__)
def test_creator_list_group_view(self): "Should use the correct view." self.assertEqual(resolve('/creators/groups/').func.__name__, views.CreatorListView.__name__)
def test_creator_detail_view(self): "Should use the correct view." IndividualCreatorFactory(name='Bob Ferris') self.assertEqual(resolve('/creators/bob-ferris/').func.__name__, views.CreatorDetailView.__name__)
def test_venue_list_view(self): "Should use the correct view." self.assertEqual(resolve('/events/venues/').func.__name__, views.VenueListView.__name__)
def test_venue_detail_view(self): "Should use the correct view." self.assertEqual(resolve('/events/venues/my-venue/').func.__name__, views.VenueDetailView.__name__) # YEARS
def test_event_year_archive_view(self): "Should use the correct view." GigEventFactory(date=('2017-02-15')) self.assertEqual(resolve('/events/2017/').func.__name__, views.EventYearArchiveView.__name__) # EVENTS
def test_event_list_view(self): "Should use the correct view." self.assertEqual(resolve('/events/gigs/').func.__name__, views.EventListView.__name__)
def test_event_detail_view(self): "Should use the correct view." self.assertEqual(resolve('/events/gigs/my-event/').func.__name__, views.EventDetailView.__name__)
def test_signed_url(): assert reverse('s3_signed_url') == '/s3/signed-url/' assert resolve('/s3/signed-url/').func == signed_url
def test_urls(): assert reverse('fake_s3_upload') == '/media/s3/uploads/' resolved = resolve('/media/s3/uploads/') assert resolved.func.__name__ == views.fake_s3_upload.__name__ ############################################################################# # fake_s3_upload #############################################################################
def process_request(self, request): host = self.get_host(request) domain, port = split_domain_port(host) if not domain: raise DisallowedHost(f'Invalid HTTP_HOST header: {host}.') request.host = domain request.port = int(port) if port else None event_slug = resolve(request.path).kwargs.get('event') if event_slug: event = get_object_or_404(Event, slug__iexact=event_slug) request.event = event if event.settings.custom_domain: custom_domain = urlparse(event.settings.custom_domain) event_domain, event_port = split_domain_port(custom_domain.netloc) if event_domain == domain and event_port == port: request.uses_custom_domain = True return else: request.needs_redirect = True return redirect(urljoin(event.settings.custom_domain, request.path)) default_domain, default_port = split_domain_port(settings.SITE_NETLOC) if domain == default_domain: return if settings.DEBUG or domain in LOCAL_HOST_NAMES: return raise DisallowedHost(f'Unknown host: {host}')
def __call__(self, request): url = resolve(request.path_info) event_slug = url.kwargs.get('event') if event_slug: request.event = get_object_or_404( Event, slug__iexact=event_slug, ) if hasattr(request, 'event') and request.event: if not request.user.is_anonymous: request.is_orga = request.user.is_superuser or EventPermission.objects.filter( user=request.user, event=request.event, is_orga=True ).exists() request.is_reviewer = request.user.is_superuser or EventPermission.objects.filter( user=request.user, event=request.event, is_reviewer=True ).exists() else: request.is_orga = False request.is_reviewer = False timezone.activate(pytz.timezone(request.event.timezone)) self._set_orga_events(request) if 'orga' in url.namespaces: url = self._handle_orga_url(request, url) if url: return redirect(url) return self.get_response(request)
def add_events(request): if request.resolver_match and request.resolver_match.namespace == 'orga' and not request.user.is_anonymous: try: url_name = resolve(request.path_info).url_name except Http404: url_name = '' return { 'events': list(Event.objects.filter(permissions__is_orga=True, permissions__user=request.user).distinct()), 'url_name': url_name, } return dict()
def bulk_destroy(self, request, *args, **kwargs): if not request.data: return Response(status=status.HTTP_400_BAD_REQUEST) qs = self.get_queryset() ids = [] for url in request.data: try: http_prefix = url.startswith(('http:', 'https:')) except AttributeError: return Response(status=status.HTTP_400_BAD_REQUEST) if http_prefix: # If needed convert absolute URLs to relative path url = urlparse(url).path prefix = get_script_prefix() if url.startswith(prefix): url = '/' + url[len(prefix):] try: match = resolve(url) except Resolver404: return Response(status=status.HTTP_400_BAD_REQUEST) try: pk = int(match.kwargs.get('pk')) except (ValueError, TypeError): return Response(status=status.HTTP_400_BAD_REQUEST) ids.append(pk) if not ids: return Response(status=status.HTTP_400_BAD_REQUEST) qs.filter(id__in=ids).delete() return Response(status=status.HTTP_204_NO_CONTENT)
def get_admin_site(context): try: current_resolver = resolve(context.get('request').path) index_resolver = resolve(reverse('%s:index' % current_resolver.namespaces[0])) if hasattr(index_resolver.func, 'admin_site'): return index_resolver.func.admin_site for func_closure in index_resolver.func.__closure__: if isinstance(func_closure.cell_contents, admin.AdminSite): return func_closure.cell_contents except: pass return admin.site
def test_all_courses(self): route = resolve('/api/course/') self.assertEqual(route.func.__name__, 'CourseListView')
def test_specific_course(self): route = resolve('/api/course/1dv702/') self.assertEqual(route.func.__name__, 'CourseView')
def test_events_for_course(self): route = resolve('/api/event/1dv702/') self.assertEqual(route.func.__name__, 'EventView')
def test_events_for_multi_courses_POST(self): route = resolve('/api/event/') self.assertEqual(route.func.__name__, 'EventView')
def test_course_codes_GET(self): route = resolve('/api/codes/') self.assertEqual(route.func.__name__, 'CourseCodeView')
def oEmbed(request): """Return an oEmbed json response.""" if 'url' not in request.GET or not request.GET.get('url'): return HttpResponseBadRequest('url parameter is required.') url = request.GET.get('url') size = request.GET.get('size', 'double') path = urlparse(url).path try: chart_kwargs = resolve(path).kwargs except NoReverseMatch: for pattern in app_settings.OEMBED_EXTRA_PATTERNS: chart_kwargs = re.search(pattern, path[1:]) if chart_kwargs is not None: chart_kwargs = chart_kwargs.groupdict() break if chart_kwargs is None: return HttpResponseNotFound( '"%s" did not match any supported oEmbed URL patterns.' % url ) try: chart = Chart.objects.get(**chart_kwargs) return JsonResponse(chart.oembed(size=size)) except Chart.DoesNotExist: return HttpResponseNotFound( 'Chart matching "%s" not found.' % chart_kwargs )