Пример #1
0
    def resolve(self, path):
        from django.core.urlresolvers import ResolverMatch
        match = self.callback(path)
        if match:
            if not isinstance(match, tuple):
                match = (match, {}, [])
            if len(match) == 1:
                match = (match[0], {})
            if len(match) == 2:
                match = (match[0], match[1], [])

            # From core/urlresolvers.py (:222 in 1.7 stable):
            # If there are any named groups, use those as kwargs, ignoring non-named
            # groups. Otherwise, pass all non-named arguments as positional
            # arguments.
            kwargs = match[1]
            if kwargs:
                args = ()
            else:
                args = match[2]

            kwargs.update({})  # TODO: extra args passed to view from urls.py
            ind = self.view.rfind('.')
            mod = self.view[:ind]
            method = self.view[(ind + 1):]
            views = importlib.import_module(mod)

            return ResolverMatch(getattr(views, method), args, kwargs, method)
Пример #2
0
    def resolve(self, path):
        # Lifted from django.core.urlresolvers.RegexURLPattern.resolve
        if not self._configured:
            raise ImproperlyConfigured('RerouteRegexURLPattern patterns must be used within reroute.patterns or reroute_patterns (for pattern %r)' % self.regex.pattern)
        
        match = self.regex.search(path)
        if match:
            # If there are any named groups, use those as kwargs, ignoring
            # non-named groups. Otherwise, pass all non-named arguments as
            # positional arguments.
            kwargs = match.groupdict()
            if kwargs:
                args = ()
            else:
                args = match.groups()
            # In both cases, pass any extra_kwargs as **kwargs.
            kwargs.update(self.default_args)

            # We unfortunately need another wrapper here since arbitrary attributes can't be set
            # on an instancemethod
            callback = lambda request, *args, **kwargs: self.reroute_callback(request, *args, **kwargs)
            
            if hasattr(self.callback, 'csrf_exempt'):
                callback.csrf_exempt = self.callback.csrf_exempt

            # Django 1.3 compatibility
            if ResolverMatch:
                return ResolverMatch(callback, args, kwargs, self.name)
            else:
                return callback, args, kwargs
Пример #3
0
 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})
Пример #4
0
 def setUp(self):
     self.keybuilder = RestApiKeyBuilder()
     self.request = HttpRequest()
     self.request.method = 'GET'
     self.request.resolver_match = ResolverMatch(func, (), {},
                                                 namespaces=['namespace'])
     self.response = HttpResponse()
Пример #5
0
    def GetFakeRequest(p_userName, p_data=None):

        from django.test import RequestFactory
        from django.core.urlresolvers import ResolverMatch

        factory = RequestFactory()

        if not p_data:
            fRequest = factory.get('')
        else:
            fRequest = factory.post('', p_data)

        try:
            user_m = AM.User.objects.get(username=p_userName)
        except AM.User.DoesNotExist:
            return None

        fRequest.user = user_m
        fRequest._dont_enforce_csrf_checks = True
        fRequest.resolver_match = ResolverMatch(func='',
                                                args=('', ),
                                                kwargs={},
                                                url_name=None,
                                                app_names=[],
                                                namespaces=[])

        return fRequest
Пример #6
0
 def resolve(self, path):
     tried = []
     found = OrderedSet()
     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 MiddlewareResolver404, 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([
                         (smart_str(k), v)
                         for k, v in match.groupdict().items()
                     ])
                     sub_match_dict.update(self.default_kwargs)
                     for k, v in sub_match.kwargs.iteritems():
                         sub_match_dict[smart_str(k)] = v
                     middleware = ResolverMatch(
                         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)
                     found.add(middleware.func)
                 tried.append([pattern])
         if len(found) == 0:
             raise MiddlewareResolver404({'tried': tried, 'path': new_path})
 def setUp(self):
     self.mw = StopWatchMiddleware()
     self.request = HttpRequest()
     self.request.method = 'GET'
     self.request.resolver_match = ResolverMatch(func, (), {},
                                                 url_name='resource_list',
                                                 namespaces=['namespace'])
     self.response = HttpResponse()
     self._statsd_patch = mock.patch('statsd.Client')
     self.mock_client = self._statsd_patch.start()
Пример #8
0
	def resolve(self, path):
		func = APP2URL.get(self.app_name, self.empty_dict).get(path, None)
		if func:
			return ResolverMatch(func, (), {}, path)
		else:
			tried = []
			for app, url2func in APP2URL.items():
				for url, func in url2func.items():
					tried.append([{'regex':{'pattern': '^{}:{}'.format(app, url)}}])
			raise Resolver404({'tried': tried, 'path' : path})
    def resolve(self, path):
        '''
        this is rewritten from django.core.urlresolvers
        because playing with URL patterns and resolvers in Django<=1.4 is weird.
        Probably because of the recursion.
        Really! Try it yourself.
        FIXME: As of Django 1.4 this shouldn't be necessary!
        '''
        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([
                            (smart_str(k), v)
                            for k, v in match.groupdict().items()
                        ])
                        sub_match_dict.update(self.default_kwargs)
                        for k, v in sub_match.kwargs.items():
                            sub_match_dict[smart_str(k)] = v
                        res_match = ResolverMatch(
                            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)
                        res_match.breadcrumb_verbose_name = getattr(
                            sub_match, 'breadcrumb_verbose_name', None)

                        return res_match
                    tried.append([pattern])
            raise Resolver404({'tried': tried, 'path': new_path})
        raise Resolver404({'path': path})
Пример #10
0
 def test_api_root_view_discard_default_django_model_permission(self):
     """
     We check that DEFAULT_PERMISSION_CLASSES can
     apply to APIRoot view. More specifically we check expected behavior of
     ``_ignore_model_permissions`` attribute support.
     """
     request = factory.get('/', format='json',
                           HTTP_AUTHORIZATION=self.permitted_credentials)
     request.resolver_match = ResolverMatch('get', (), {})
     response = api_root_view(request)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Пример #11
0
    def resolve(self, path):
        method = None
        app_resource = None
        func = None
        try:
            items = path.split('/')

            #特殊处理apps的app_name
            app_name = self.app_name
            if app_name == 'apps':
                app_name = 'apps/%s' % items[0]
                items.remove(items[0])

            method = items[-1].lower()
            if items[0] == 'api':
                resource = '/'.join(items[1:-1])
                method = 'api_%s' % method
            else:
                resource = '/'.join(items[:-1])

            app_resource = '%s-%s' % (app_name, resource)
            class_info = resource_util.APPRESOURCE2CLASS.get(
                app_resource, None)
            # print '-*-' * 20
            # print 'path: ', path
            # print 'method: ', method
            # print 'app_resource: ', app_resource
            # print '-$-' * 20
            if class_info:
                if not class_info['instance']:
                    class_info['instance'] = class_info['cls']
                resource_instance = class_info['instance']
                func = getattr(resource_instance, method, None)
                if func:
                    return ResolverMatch(func, (), {}, path)
                else:
                    self.__raise_404(path)
            else:
                self.__raise_404(path)
        except:
            context = {
                'path': path,
                'method': method,
                'app_resource': app_resource,
                'func': func,
                'APPRESOURCE2CLASS': resource_util.APPRESOURCE2CLASS
            }
            self.__raise_404(path)
Пример #12
0
	def resolve(self, path):
		method = None
		app_resource = None
		func = None
		try:
			items = [self.app_name]
			items.extend(path.split('/'))
			print items

			method = items[-1].lower()
			resource = items[-2]
			if items[-3] == 'api':
				app_name = '.'.join(items[:-3])
				method = 'api_%s' % method
			else:
				app_name = '.'.join(items[:-2])
			
			app_resource = '%s-%s' % (app_name, resource)
			class_info = resource_util.APPRESOURCE2CLASS.get(app_resource, None)
			if class_info:
				if not class_info['instance']:
					class_info['instance'] = class_info['cls']
				resource_instance = class_info['instance']
				func = getattr(resource_instance, method, None)
				if func:
					return ResolverMatch(func, (), {}, path)
				else:
					self.__raise_404(path)
			else:
				self.__raise_404(path)
		except:
			import sys
			import traceback
			a, b, c = sys.exc_info()
			print a
			print b
			traceback.print_tb(c)
			context = {
				'path': path,
				'method': method,
				'app_resource': app_resource,
				'func': func,
				'APPRESOURCE2CLASS': resource_util.APPRESOURCE2CLASS
			}
			self.__raise_404(path)
Пример #13
0
 def resolve(self, path):
     self.regex.pattern = '{}/{}'.format(self.app_dir, path)
     if not self.is_func_loaded:
         self.__load_api_func()
     func = self.__get_api_func(path)
     if func:
         return ResolverMatch(func, (), {}, path)
     else:
         if self.__should_update_loaded_files():
             self.is_func_loaded = False
             self.loaded_file_set = None
             self.name2func = {}
             return self.resolve(path)
         else:
             tried = []
             for key in self.name2func:
                 tried.append([{'regex': {'pattern': '^{}/$'.format(key)}}])
             raise Resolver404({'tried': tried, 'path': path})
Пример #14
0
    def test_load_extensions_js_tag(self):
        """Testing load_extensions_js template tag"""
        t = Template('{% load djblets_extensions %}'
                     '{% load_extensions_js manager_id %}')

        self.request.resolver_match = ResolverMatch(None, None, None, 'foo')

        self.assertEqual(
            t.render(
                Context({
                    'ext': self.extension,
                    'manager_id': self.key,
                    'request': self.request,
                })),
            '/ext/djblets.extensions.templatetags.tests.TestExtension/js/'
            'default.min.js\n'
            '/ext/djblets.extensions.templatetags.tests.TestExtension/js/'
            'optional.min.js\n')
Пример #15
0
    def test_dispatch_with_no_local_site(self):
        """Testing CheckLocalSiteAccessViewMixin.dispatch with no LocalSite"""
        class MyView(CheckLocalSiteAccessViewMixin, View):
            def get(view, *args, **kwargs):
                self.assertIsNone(view.local_site)

                return HttpResponse('success')

        view = MyView.as_view()

        request = RequestFactory().request()
        request.resolver_match = ResolverMatch(view, [], {})
        request.local_site = None
        request.user = User.objects.get(username='******')

        response = view(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, 'success')
Пример #16
0
    def resolve(self, path):
        method = None
        app_resource = None
        func = None
        try:
            items = path.split('/')
            method = items[-1].lower()
            if items[0] == 'api':
                resource = '/'.join(items[1:-1])
                method = 'api_%s' % method
            else:
                resource = '/'.join(items[:-1])

            app_resource = '%s-%s' % (self.app_name, resource)
            class_info = resource_util.APPRESOURCE2CLASS.get(
                app_resource, None)
            # print '-*-' * 20
            # print 'path: ', path
            # print 'method: ', method
            # print 'app_resource: ', app_resource
            # print '-$-' * 20
            if class_info:
                if not class_info['instance']:
                    class_info['instance'] = class_info['cls']
                resource_instance = class_info['instance']
                func = getattr(resource_instance, method, None)
                if func:
                    return ResolverMatch(func, (), {}, path)
                else:
                    self.__raise_404(path)
            else:
                self.__raise_404(path)
        except:
            context = {
                'path': path,
                'method': method,
                'app_resource': app_resource,
                'func': func,
                'APPRESOURCE2CLASS': resource_util.APPRESOURCE2CLASS
            }
            notify_message = u"RESTful url2 route failed, context:{}\ncause:\n{}".format(
                str(context), unicode_full_stack())
            # watchdog_fatal(notify_message, type='URL_ROUTE', noraise=True)
            self.__raise_404(path)
Пример #17
0
    def resolve(self, path):
        """
        Match path to Page object and return its registered view
        """
        # Clean up and check path
        path = force_text(path)  # path may be a reverse_lazy object
        if path and not path.endswith('/'):
            # If we don't have a / at the end, we bail. If APPEND_SLASH is set,
            # this will redirect it to the view with a /
            raise Resolver404({'tried': [], 'path': path})

        # Get the associated page
        page, page_slug, subpage_slugs = self.find_page_for_path(path)

        # Fetch the View class
        view_class = page.view_class

        # The view specifies if it allows subpages. We raise Resolver404 to
        # allow other patterns below this one in the urlconf
        if not view_class.allows_subpages and subpage_slugs:
            raise Resolver404({'tried': [], 'path': path})

        # If we have an ApplicationView, we need to go deeper
        if issubclass(view_class, ApplicationView):
            resolver = self.get_subresolver(view_class, page.path)
            try:
                return resolver.resolve(path)
            except Resolver404 as e:
                # Add PageResolver as base to the tried patterns
                sub_tried = e.args[0].get('tried') or []
                raise Resolver404({
                    'path': path,
                    'tried': [[resolver] + t for t in sub_tried]
                })
        else:
            kwargs = {
                'page': page,
                'slug': page_slug,
                'subpage_slugs': subpage_slugs,
            }
            return ResolverMatch(view_class.as_view(), [],
                                 kwargs,
                                 app_name=self.app_name,
                                 namespaces=[self.namespace])
Пример #18
0
    def test_init_js_extensions(self):
        """Testing init_js_extensions template tag"""
        t = Template('{% load djblets_extensions %}'
                     '{% init_js_extensions manager_id %}')

        self.request.resolver_match = ResolverMatch(None, None, None, 'foo')

        content = t.render(
            Context({
                'ext': self.extension,
                'manager_id': self.key,
                'request': self.request,
            }))

        self.assertIsNotNone(
            re.search(r'new FooNew\({\s+"test": "new",', content))

        self.assertIsNotNone(
            re.search(r'new FooOld\({\s+"test": "old",', content))
Пример #19
0
    def test_load_extensions_js_tag(self):
        """Testing load_extensions_js template tag"""
        t = Template('{% load djblets_extensions %}'
                     '{% load_extensions_js manager_id %}')

        self.request.resolver_match = ResolverMatch(None, None, None, 'foo')

        self.assertEqual(
            t.render(
                Context({
                    'ext': self.extension,
                    'manager_id': self.key,
                    'request': self.request,
                })), '<script type="text/javascript" '
            'src="/ext/djblets.extensions.tests.test_templatetag'
            's.TestExtension/js/default.min.js" charset="utf-8"></script>\n'
            '<script type="text/javascript" '
            'src="/ext/djblets.extensions.tests.test_templatetag'
            's.TestExtension/js/optional.min.js" charset="utf-8"></script>\n')
Пример #20
0
    def test_dispatch_with_local_site_and_anonymous(self):
        """Testing CheckLocalSiteAccessViewMixin.dispatch with LocalSite and
        anonymous user
        """
        class MyView(CheckLocalSiteAccessViewMixin, View):
            def get(view, *args, **kwargs):
                self.assertIsNotNone(view.local_site)
                self.assertEqual(view.local_site.name, 'local-site-1')

                return HttpResponse('success')

        view = MyView.as_view()

        request = RequestFactory().request()
        request.resolver_match = ResolverMatch(view, [], {})
        request.local_site = LocalSite.objects.get(name='local-site-1')
        request.user = AnonymousUser()

        response = view(request, local_site_name='local-site-1')
        self.assertIsInstance(response, HttpResponseRedirect)
Пример #21
0
    def test_load_extensions_css_tag(self):
        """Testing load_extensions_css template tag"""
        t = Template('{% load djblets_extensions %}'
                     '{% load_extensions_css manager_id %}')

        self.request.resolver_match = ResolverMatch(None, None, None, 'foo')

        self.assertEqual(
            t.render(
                Context({
                    'ext': self.extension,
                    'manager_id': self.key,
                    'request': self.request,
                })),
            '<link href="/ext/djblets.extensions.tests.test_templatetags'
            '.TestExtension/css/default.min.css" rel="stylesheet" '
            'type="text/css" />\n'
            '<link href="/ext/djblets.extensions.tests.test_templatetags'
            '.TestExtension/css/optional.min.css" rel="stylesheet" '
            'type="text/css" />\n')
Пример #22
0
    def test_dispatch_with_local_site_and_not_allowed(self):
        """Testing CheckLocalSiteAccessViewMixin.dispatch with LocalSite and
        access not allowed
        """
        class MyView(CheckLocalSiteAccessViewMixin, View):
            def get(view, *args, **kwargs):
                self.assertIsNotNone(view.local_site)
                self.assertEqual(view.local_site.name, 'local-site-1')

                return HttpResponse('success')

        view = MyView.as_view()

        request = RequestFactory().request()
        request.resolver_match = ResolverMatch(view, [], {})
        request.local_site = LocalSite.objects.get(name='local-site-1')
        request.user = User.objects.create(username='******')

        response = view(request, local_site_name='local-site-1')
        self.assertEqual(response.status_code, 403)
Пример #23
0
    def resolve(self, path):
        items = path.split('/')
        method = items[-1].lower()
        if items[0] == 'api':
            resource = '/'.join(items[1:-1])
            method = 'api_%s' % method
        else:
            resource = '/'.join(items[:-1])

        app_resource = '%s-%s' % (self.app_name, resource)
        class_info = resource_util.APPRESOURCE2CLASS.get(app_resource, None)
        if class_info:
            if not class_info['instance']:
                class_info['instance'] = class_info['cls']
            resource_instance = class_info['instance']
            func = getattr(resource_instance, method, None)
            if func:
                return ResolverMatch(func, (), {}, path)
            else:
                self.__raise_404(path)
        else:
            self.__raise_404(path)
Пример #24
0
    def test_load_extensions_css_tag_with_pipline_disabled(self):
        """Testing load_extensions_css template tag with PIPELINE_ENABLED=False
        """
        pipeline_settings.PIPELINE_ENABLED = False

        t = Template('{% load djblets_extensions %}'
                     '{% load_extensions_css manager_id %}')

        self.request.resolver_match = ResolverMatch(None, None, None, 'foo')

        self.assertHTMLEqual(
            t.render(
                Context({
                    'ext': self.extension,
                    'manager_id': self.key,
                    'request': self.request,
                })),
            '<link href="/ext/djblets.extensions.tests.test_templatetags'
            '.TestExtension/css/default-test.dad0c9b31e59.css" '
            'rel="stylesheet" type="text/css" />'
            '<link href="/ext/djblets.extensions.tests.test_templatetags'
            '.TestExtension/css/optional-test.dad0c9b31e59.css" '
            'rel="stylesheet" type="text/css" />')
Пример #25
0
    def test_load_extensions_js_tag_with_pipeline_disabled(self):
        """Testing load_extensions_js template tag with PIPELINE_ENABLED=False
        """
        pipeline_settings.PIPELINE_ENABLED = False

        t = Template('{% load djblets_extensions %}'
                     '{% load_extensions_js manager_id %}')

        self.request.resolver_match = ResolverMatch(None, None, None, 'foo')

        self.assertHTMLEqual(
            t.render(
                Context({
                    'ext': self.extension,
                    'manager_id': self.key,
                    'request': self.request,
                })), '<script type="text/javascript" '
            'src="/ext/djblets.extensions.tests.test_templatetags'
            '.TestExtension/js/default-test.dad0c9b31e59.js" '
            'charset="utf-8"></script>'
            '<script type="text/javascript" '
            'src="/ext/djblets.extensions.tests.test_templatetags'
            '.TestExtension/js/optional-test.dad0c9b31e59.js" '
            'charset="utf-8"></script>')
Пример #26
0
 def run_view_test(self, view, user):
     return user_can_see_view(ResolverMatch(view, [], {}), user)
Пример #27
0
def get_resolver_match(url_name='dr_pepper', app_name='sodas'):
    """Resolve a url back to a view."""
    return ResolverMatch(None, [], {}, url_name=url_name, app_name=app_name)