I am working with weasyprint after I migrated from xhtml2pdf, and I am finding some issue with getting static files. I get the following error:
2021-12-03 14:45:50,198 [ERROR] Failed to load image at "http://api.dashboard.localhost:8000/static/logos/logo.png" (URLError: <urlopen error [Errno -2] Name or service not known>)
but when I access the same URL weasyprint couldn't, either on my browser or curl, I am able to view/ access the file.
Here is my code:
from io import BytesIO
import mimetypes
from pathlib import Path
from urllib.parse import urlparse
import logging
from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.core.files.storage import default_storage
from django.urls import get_script_prefix
from django.template.loader import render_to_string
import weasyprint
from weasyprint import HTML
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
# https://github.com/fdemmer/django-weasyprint/blob/main/django_weasyprint/utils.py
def url_fetcher(url, *args, **kwargs):
# load file:// paths directly from disk
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,
}
default_media_url = settings.MEDIA_URL in ('', get_script_prefix())
if not default_media_url and url_path.startswith(settings.MEDIA_URL):
media_root = settings.MEDIA_ROOT
if isinstance(settings.MEDIA_ROOT, Path):
media_root = f'{settings.MEDIA_ROOT}/'
path = url_path.replace(settings.MEDIA_URL, media_root, 1)
data['file_obj'] = default_storage.open(path)
return data
elif settings.STATIC_URL and url_path.startswith(settings.STATIC_URL):
path = url_path.replace(settings.STATIC_URL, '', 1)
data['file_obj'] = open(find(path), 'rb')
return data
# fall back to weasyprint default fetcher
return weasyprint.default_url_fetcher(url, *args, **kwargs)
def render_template_to_pdf(template_path, request, context):
results = BytesIO()
template_string = render_to_string(
template_name=template_path,
context=context,
)
# create the pdf report
HTML(string=template_string, base_url=request.build_absolute_uri("/"), url_fetcher=url_fetcher).write_pdf(results)
return results.getbuffer()
The above code generates the pdf, but with no images as the above mentioned error keeps showing in my logs.
My settings for media/ static files:
DEFAULT_FILE_STORAGE = "utils.storages.CustomFileSystemStorage"
STATIC_URL = "/static/"
STATIC_ROOT = os.path.realpath(env.str("STATIC_FILES_ROOT", default=os.path.join(BASE_DIR, "staticfiles") "/"))
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.realpath(env.str("MEDIA_FILES_ROOT", default=os.path.join(BASE_DIR, "mediafiles") "/"))
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
In my template:
{% load static %}
<div style="float: right;">
<img src="{% static 'logos/logo.jpg' %}" alt="logo" width="140" height="40"/>
</div>
I am running this in docker, but I think it may not be relevant since I could access the files outside the application (browser/ curl) but not with weasyprint.
I have been checking answers on stackoverflow/github/etc but couldn't find something explaining why is this happening or how to work around it unfortunately. Any insights on why this is happening are very appreciated!
CodePudding user response:
Docker is not the issue because I'm also getting similar error while using static the same way you did without a docker. I'm getting the error shown below:
[weasyprint:137] ERROR: Relative URI reference without a base URI:
So what I did is i used urlsplit to get my app url and I passed it to template so that i can use full url.
from django.utils.six.moves.urllib.parse import urlsplit
def test(request):
scheme = urlsplit(request.build_absolute_uri(None))
context = {
'host_url': f"{scheme.scheme}://{scheme.netloc}"
}
return render(request, 'pdf.html', context)
template
<img src="{{ host_url }}/logos/logo.jpg" alt="" />
Instead of passing host_url you can directly use your domain but using host_url it makes app dynamic and you don't have to change domain while you're in different domain or while using in local server.
CodePudding user response:
I am not sure why, but setting base_url
to "."
resolves the issue and weasyprint can now resolve both local and external static files.
Change takes effect in:
HTML(string=template_string, base_url=".", url_fetcher=url_fetcher).write_pdf(results)
This took me the whole day and I looked into the source code of both weasyprint and django-weasyprint before attempting the "."
. I hope this saves anyone with same issue some time in the future.