Skip to content

Commit 59812ed

Browse files
committed
Add ability to parse static path before using it as though it was
a relative filesystem path. Thereby enabling developers to add the versioning string as a component in the path rather than a query string. Which is required when working with CloudFront for instance.
1 parent 782c4de commit 59812ed

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

tornado/test/web_test.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -552,12 +552,24 @@ class CustomStaticFileTest(AsyncHTTPTestCase, LogTrapTestCase):
552552
def get_app(self):
553553
class MyStaticFileHandler(StaticFileHandler):
554554
def get(self, path):
555+
path = self.parse_url_path(path)
555556
assert path == "foo.txt"
556557
self.write("bar")
557558

558559
@classmethod
559560
def make_static_url(cls, settings, path):
560-
return "/static/%s?v=42" % path
561+
version_hash = cls.get_version(settings, path)
562+
extension_index = path.rindex('.')
563+
before_version = path[:extension_index]
564+
after_version = path[(extension_index + 1):]
565+
return '/static/%s.%s.%s' % (before_version, 42, after_version)
566+
567+
@classmethod
568+
def parse_url_path(cls, url_path):
569+
extension_index = url_path.rindex('.')
570+
version_index = url_path.rindex('.', 0, extension_index)
571+
return '%s%s' % (url_path[:version_index],
572+
url_path[extension_index:])
561573

562574
class StaticUrlHandler(RequestHandler):
563575
def get(self, path):
@@ -568,9 +580,9 @@ def get(self, path):
568580
static_handler_class=MyStaticFileHandler)
569581

570582
def test_serve(self):
571-
response = self.fetch("/static/foo.txt")
583+
response = self.fetch("/static/foo.42.txt")
572584
self.assertEqual(response.body, b("bar"))
573585

574586
def test_static_url(self):
575587
response = self.fetch("/static_url/foo.txt")
576-
self.assertEqual(response.body, b("/static/foo.txt?v=42"))
588+
self.assertEqual(response.body, b("/static/foo.42.txt"))

tornado/web.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1446,6 +1446,7 @@ def head(self, path):
14461446
def get(self, path, include_body=True):
14471447
if os.path.sep != "/":
14481448
path = path.replace("/", os.path.sep)
1449+
path = self.parse_url_path(path)
14491450
abspath = os.path.abspath(os.path.join(self.root, path))
14501451
# os.path.abspath strips a trailing /
14511452
# it needs to be temporarily added back for requests to root/
@@ -1558,6 +1559,10 @@ def get_version(cls, settings, path):
15581559
return hsh[:5]
15591560
return None
15601561

1562+
@classmethod
1563+
def parse_url_path(cls, url_path):
1564+
return url_path
1565+
15611566

15621567
class FallbackHandler(RequestHandler):
15631568
"""A RequestHandler that wraps another HTTP server callback.

0 commit comments

Comments
 (0)