From 33b638478a5d4e9d3190ec0130902091817601a0 Mon Sep 17 00:00:00 2001 From: Tom Lazar Date: Sat, 17 Aug 2013 12:24:23 +0200 Subject: assemble a custom pregenerator for static external urls we split the pattern via urlparse and pass the parts into the pregenerator such that route_url will behave as expected, mainly by assembling an appropriate value for ``_app_url`` --- pyramid/config/routes.py | 18 ++++++++++++++++++ pyramid/tests/test_url.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/pyramid/config/routes.py b/pyramid/config/routes.py index c86e4a2dd..f4f9ac888 100644 --- a/pyramid/config/routes.py +++ b/pyramid/config/routes.py @@ -1,4 +1,5 @@ import warnings +from urlparse import urlparse from pyramid.interfaces import ( IRequest, @@ -387,6 +388,23 @@ class RoutesConfiguratorMixin(object): if self.route_prefix: pattern = self.route_prefix.rstrip('/') + '/' + pattern.lstrip('/') + if pregenerator is None: + parsed = urlparse(pattern) + if parsed.hostname: + pattern = parsed.path + + def external_url_pregenerator(request, elements, kw): + if '_scheme' in kw and parsed.scheme != kw['_scheme']: + scheme = kw['_scheme'] + elif parsed.scheme: + scheme = parsed.scheme + else: + scheme = request.scheme + kw['_app_url'] = '{0}://{1}'.format(scheme, parsed.netloc) + return elements, kw + + pregenerator = external_url_pregenerator + mapper = self.get_routes_mapper() introspectables = [] diff --git a/pyramid/tests/test_url.py b/pyramid/tests/test_url.py index bf1c514c5..c7b8cfca1 100644 --- a/pyramid/tests/test_url.py +++ b/pyramid/tests/test_url.py @@ -1027,6 +1027,41 @@ class Test_current_route_path(unittest.TestCase): self.assertEqual(request.elements, ('abc',)) self.assertEqual(request.kw, {'_anchor':'abc'}) +class Test_external_static_url_integration(unittest.TestCase): + + def setUp(self): + self.config = testing.setUp() + + def tearDown(self): + testing.tearDown() + + def _makeRequest(self): + from pyramid.request import Request + return Request.blank('/') + + def test_generate_external_url(self): + self.config.add_route('acme', 'https://acme.org/path/{foo}') + request = self._makeRequest() + request.registry = self.config.registry + self.assertEqual(request.route_url('acme', foo='bar'), + 'https://acme.org/path/bar') + + def test_generate_external_url_without_scheme(self): + self.config.add_route('acme', '//acme.org/path/{foo}') + request = self._makeRequest() + request.registry = self.config.registry + self.assertEqual(request.route_url('acme', foo='bar'), + 'http://acme.org/path/bar') + + + def test_generate_external_url_with_explicit_scheme(self): + self.config.add_route('acme', '//acme.org/path/{foo}') + request = self._makeRequest() + request.registry = self.config.registry + self.assertEqual(request.route_url('acme', foo='bar', _scheme='https'), + 'https://acme.org/path/bar') + + class DummyContext(object): def __init__(self, next=None): self.next = next -- cgit v1.2.3