Skip to content

Instantly share code, notes, and snippets.

@birkin
Created November 15, 2024 19:23
Show Gist options
  • Save birkin/2a786c7189a9c27fbb9532bb8f138b12 to your computer and use it in GitHub Desktop.
Save birkin/2a786c7189a9c27fbb9532bb8f138b12 to your computer and use it in GitHub Desktop.
example of rendering xml via django template
"""
Generates XML output using Django's template system.
Accepts command-line arguments to specify a person's name and role.
Usage:
$ uv run "./render_xml_via_template.py" --person "Birkin" --role "cheerleader"
Output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<name>Birkin</name>
<role>cheerleader</role>
</item>
</root>
"""
# /// script
# requires-python = ">=3.8, <3.9"
# dependencies = [
# "django~=3.2.0",
# ]
# ///
import argparse
from django.template import Context, Engine
## this would normally be a separate file
XML_TEMPLATE_STRING = """<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<name>{{ person }}</name>
<role>{{ role }}</role>
</item>
</root>"""
def render_xml(context_data) -> str:
# Create an engine instance to compile and render the template
engine = Engine()
template = engine.from_string(XML_TEMPLATE_STRING)
# Render the XML using the provided context
context = Context(context_data)
xml_content = template.render(context)
# Return the rendered XML content
return xml_content
def grab_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description='Generate XML with person and role information.')
parser.add_argument('--person', type=str, required=True, help='The name of the person')
parser.add_argument('--role', type=str, required=True, help='The role of the person')
return parser.parse_args()
def main():
## get args -----------------------------------------------------
args: argparse.Namespace = grab_args()
## prep context -------------------------------------------------
context_data = {'person': args.person, 'role': args.role}
## render -------------------------------------------------------
xml_output: str = render_xml(context_data)
print(xml_output)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment