This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
51 lines (39 loc) · 1.54 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Documents generation utilities."""
import mimetypes
from pathlib import Path
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.core.exceptions import SuspiciousFileOperation
import weasyprint
def static_file_fetcher(url, *args, **kwargs):
"""Weasyprint static files fetcher.
If the file URL starts with 'file://', it will be fetched from the configured
storage.
The following code has been adapted from the django-weasyprint project [1].
References:
[1] https://github.com/fdemmer/django-weasyprint/
"""
if url.startswith("file:"):
mime_type, encoding = mimetypes.guess_type(url)
url_path = urlparse(url).path
data = {
"mime_type": mime_type,
"encoding": encoding,
"filename": Path(url_path).name,
}
path = url_path.replace(settings.STATIC_URL, "", 1)
try:
data["file_obj"] = open( # pylint: disable=consider-using-with
find(path), "rb"
)
# A SuspiciousFileOperation is raised by Django if the file has been
# found outside referenced static file paths. In this case, we ignore
# this error and fallback to the default Weasyprint fetcher for files
# referenced with the file:// protocol.
except SuspiciousFileOperation:
pass
else:
return data
# Fall back to weasyprint default fetcher
return weasyprint.default_url_fetcher(url, *args, **kwargs)