AlexW AlexW - 5 months ago 43
Python Question

Jinja2 dump into an object?

I want to be able to dump into an object.

According to the documentation, I can dump into a file or a file like object.

What can I use as a file like object?

Obs.: I don't want to save it nor display it. Its a downloadable config template for a router thats created on the fly from data stored in the database.

env = Environment(autoescape=False, optimized=False)

config_file = None
device_config = None
device_config = env.from_string(config_template.config)
device_config.stream(
STR = site.location.upper()[:4],
).dump(config_file)


Reason being is I want to use a content disposition to output the file to a users browser with django.

EDIT:
tested with stringIO

import StringIO
>>> config_file = StringIO
>>> device_config = None
>>> device_config = env.from_string(config_template.config)
>>> device_config.stream(
... STR = site.location.upper()[:4],
... ).dump(config_file)
Traceback (most recent call last):
File "<console>", line 3, in <module>
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 1167, in dump
fp.write(item)
AttributeError: 'module' object has no attribute 'write'
>>>


Thanks

Aya Aya
Answer

I've never used jinja2, but I suspect you can use a StringIO to get the desired content as a string.

The following ought to work, but I can't (easily) test it...

from StringIO import StringIO

env = Environment(autoescape=False, optimized=False)

sio = StringIO()

device_config = env.from_string(config_template.config)
device_config.stream(
  STR         = site.location.upper()[:4],
).dump(sio)

content = sio.getvalue()

However, if you just want a string, it looks like you should use the render() method instead...

env = Environment(autoescape=False, optimized=False)

device_config = env.from_string(config_template.config)
content = device_config.render(
  STR         = site.location.upper()[:4],
)

...but, again, I can't easily test it.

Comments