Skip to content

Commit

Permalink
Handle un-hashed filenames with ManifestStaticFilesStorage and DEBUG=…
Browse files Browse the repository at this point in the history
…True
  • Loading branch information
fdemmer committed Feb 23, 2024
1 parent 33767a7 commit 7c19e40
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [2.3.0] - 2024-02-23

- Make it possible to set [WeasyPrint options][2] via `WeasyTemplateResponse` (#79)
- Add support for non-hashed path when `ManifestStaticFilesStorage` is used with `DEBUG=True`

[2]: https://doc.courtbouillon.org/weasyprint/stable/api_reference.html#weasyprint.DEFAULT_OPTIONS

Expand Down
1 change: 1 addition & 0 deletions django_weasyprint/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@


settings.configure(
DEBUG=False,
SECRET_KEY=get_random_secret_key(),
ALLOWED_HOSTS=['testserver'],
ROOT_URLCONF=__name__,
Expand Down
12 changes: 12 additions & 0 deletions django_weasyprint/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,18 @@ def test_manifest_static(self, mock_fetcher, mock_find, mock_open, hashed_files)
mock_open.assert_called_once_with('/www/static/css/styles.css', 'rb')
self.assert_data(data, '/www/static/css/styles.css', 'text/css')

mock_find.reset_mock()
mock_open.reset_mock()

# ManifestStaticFilesStorage.url() returns un-hashed URL with DEBUG=True,
# django_url_fetcher() is still able to find the file.
with override_settings(DEBUG=True):
data = django_url_fetcher('file:///static/css/styles.css')
mock_fetcher.assert_not_called()
mock_find.assert_called_once_with('css/styles.css')
mock_open.assert_called_once_with('/www/static/css/styles.css', 'rb')
self.assert_data(data, '/www/static/css/styles.css', 'text/css')

@override_settings(STATIC_URL='/static/', STATIC_ROOT='/www/static')
@mock.patch('django_weasyprint.utils.open')
@mock.patch('django_weasyprint.utils.find', return_value=None)
Expand Down
2 changes: 1 addition & 1 deletion django_weasyprint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def django_url_fetcher(url, *args, **kwargs):
# strip the STATIC_URL prefix to get the relative filesystem path
relative_path = url_path.replace(settings.STATIC_URL, '', 1)
# detect hashed files storage and get path with un-hashed filename
if hasattr(staticfiles_storage, 'hashed_files'):
if not settings.DEBUG and hasattr(staticfiles_storage, 'hashed_files'):
log.debug('Hashed static files storage detected')
relative_path = get_reversed_hashed_files()[relative_path]
data['filename'] = Path(relative_path).name
Expand Down

0 comments on commit 7c19e40

Please sign in to comment.