Weasyprint Turn Off all the Warnings
Using WeasyPrint but it is always overwhelming me with INFO, DEBUB messages.
How do I turn them all off? Nothing i have tried works. (Using Django)
Thanks
If it's during PDF generation - the below works in FastAPI
contexts (and my use-case was converting HTML to PDF), and I don't see any reasons why it wouldn't also work in Django
or for other generation steps.
Beware that it is... not necessarily a hack, but also not a very clean approach - it interferes with OS-level behavior, and so might not be super stable for all environments or concurrent execution paths.
What it does is basically redirecting stderr
to somewhere you can't see it for a manager-given execution context, then resetting it to normal afterwards:
import contextlib
import sys
import tempfile
from weasyprint import HTML
@contextlib.contextmanager
def suppress_stderr():
with tempfile.TemporaryFile() as f:
stderr_fd = sys.stderr.fileno()
sys.stderr.flush()
saved_stderr_fd = os.dup(stderr_fd)
os.dup2(f.fileno(), stderr_fd)
try:
yield
finally:
os.dup2(saved_stderr_fd, stderr_fd)
os.close(saved_stderr_fd)
with tempfile.NamedTemporaryFile(delete=False, dir=PDF_TMP_PATH, suffix='.pdf') as pdf:
try:
with suppress_stderr():
HTML(string=content).write_pdf(pdf.name)
except Exception as e:
...