AWS Lambda Python Jinja2 Template load json from S3

Viewed 408

I am looking to fetch a json structured Jinja2 template (a json with j2 variables) from S3 bucket and render with key values. I see 2 road blocks that I need help with:

  1. Template module has PackageLoader and similar but I couldn't find a loader from S3 bucket. If not, is doing an S3 object download onto my AWS lambda memory a good choice?
env = Environment(loader=FileSystemLoader (OR PackageLoader('app','templates'))
template_source = env.loader.get_source(env, 'sample.json')
  1. How do I use Template() to load a json style jinja file? When I try below code, it errors stating that "Expecting property name enclosed in double quotes"
        response = s3.get_object(Bucket=bucket, Key="sample.json")
        data = response['Body'].read()
        template = Template(data) #errors here

Appreciate your inputs here, thank you.

1 Answers

The issue is that S3 read() returns bytes, so you have to decoded to utf8 for jinja2 to work:

response['Body'].read().decode('utf-8')
Related