inventory/inventory/debug_pretty.py
2025-09-22 14:08:24 -05:00

31 lines
1,004 B
Python

from flask import request
from werkzeug.wrappers.response import Response
def init_pretty(app):
@app.after_request
def _pretty_html(resp: Response):
if not app.debug:
print("Not debugging.")
return resp
if resp.mimetype != "text/html":
return resp
if request.args.get("pretty") != "1":
return resp
html = resp.get_data(as_text=True)
try:
# Prefer lxml if present; falls back to bs4
from lxml import html as lhtml
pretty = lhtml.tostring(
lhtml.fromstring(html),
encoding="unicode",
method="html",
pretty_print=True,
)
except Exception:
from bs4 import BeautifulSoup
pretty = BeautifulSoup(html, "html.parser").prettify(formatter="html")
resp.set_data(pretty)
resp.headers["Content-Length"] = str(len(pretty.encode("utf-8")))
return resp