Refactor HTML generation and add template argument

Centralized HTML content generation logic into a single function `generate_html`, replacing `generate_monthly_html`, `generate_weekly_html`, and `generate_daily_html`. This simplifies the handling of different content types and allows for dynamic template path specification via command-line arguments, enhancing flexibility. The refactoring also includes argument validation for the calendar type, ensuring that unsupported types are not processed.
This commit is contained in:
Kumi 2023-12-26 22:06:18 +01:00
parent c08de0fd30
commit e9cc432e29
Signed by: kumi
GPG key ID: ECBCC9082395383F

View file

@ -87,25 +87,25 @@ def get_week(
week_days.append(day_info) week_days.append(day_info)
return week_days return week_days
def generate_html(content, content_type, template_path: str = None):
if not template_path:
template_name = "{}.html".format(content_type)
file_loader = FileSystemLoader(Path(__file__).parent.absolute() / "templates")
else:
template_name = template_path
file_loader = FileSystemLoader()
def generate_monthly_html(month):
file_loader = FileSystemLoader(Path(__file__).parent.absolute() / "templates")
env = Environment(loader=file_loader) env = Environment(loader=file_loader)
template = env.get_template("monthly.html") template = env.get_template(template_name)
return template.render(month=month, month_obj=month[1][0]["date_obj"])
if content_type == "monthly":
def generate_weekly_html(week): return template.render(month=content, month_obj=content[1][0]["date_obj"])
file_loader = FileSystemLoader(Path(__file__).parent.absolute() / "templates") elif content_type == "weekly":
env = Environment(loader=file_loader) return template.render(week=content)
template = env.get_template("weekly.html") elif content_type == "daily":
return template.render(week=week) return template.render(day=content)
else:
def generate_daily_html(day): raise ValueError("Invalid content type: {}".format(content_type))
file_loader = FileSystemLoader(Path(__file__).parent.absolute() / "templates")
env = Environment(loader=file_loader)
template = env.get_template("daily.html")
return template.render(day=day)
def convert_html_to_pdf(content, output_filename, options=None): def convert_html_to_pdf(content, output_filename, options=None):
options.setdefault("page-size", "A4") options.setdefault("page-size", "A4")
@ -140,6 +140,13 @@ def main():
required=False, required=False,
default="%b %d, %Y", default="%b %d, %Y",
) )
parser.add_argument(
"--template",
"-T",
help="Template to use",
required=False,
default=None,
)
type_group = parser.add_mutually_exclusive_group() type_group = parser.add_mutually_exclusive_group()
type_group.add_argument( type_group.add_argument(
@ -235,26 +242,22 @@ def main():
except ValueError: except ValueError:
start_date = start_date.replace(year=start_date.year + 1, month=1) start_date = start_date.replace(year=start_date.year + 1, month=1)
if args.type == "daily": if not args.type in ["daily", "weekly", "monthly"]:
for i in range(count): raise ValueError(f"Invalid calendar type: {args.type}")
day = get_day(for_date, country_code, args.date_format)
html_content = generate_daily_html(day) for i in range(count):
pages.append(html_content) data = ({
for_date = day["date_obj"] + timedelta(days=1) "daily": get_day,
elif args.type == "weekly": "weekly": get_week,
for i in range(count): "monthly": get_month
week = get_week(for_date, country_code, args.date_format) }[args.type])(for_date, country_code, args.date_format)
html_content = generate_weekly_html(week) html_content = generate_html(data, args.type, args.template)
pages.append(html_content) pages.append(html_content)
for_date = week[-1]["date_obj"] + timedelta(days=1) for_date = {
elif args.type == "monthly": "daily": lambda x: x["date_obj"] + timedelta(days=1),
for i in range(count): "weekly": lambda x: x[-1]["date_obj"] + timedelta(days=1),
month = get_month(for_date, country_code, args.date_format) "monthly": lambda x: x[1][0]["date_obj"] + timedelta(days=31)
html_content = generate_monthly_html(month) }[args.type](data)
pages.append(html_content)
for_date = month[1][0]["date_obj"] + timedelta(days=31)
else:
raise NotImplementedError(f"Calendar type {args.type} is not supported")
conversion_options = {"orientation": "Portrait"} if args.type == "daily" else {} conversion_options = {"orientation": "Portrait"} if args.type == "daily" else {}
convert_html_to_pdf("\n".join(pages), args.output, options=conversion_options) convert_html_to_pdf("\n".join(pages), args.output, options=conversion_options)