Reputation: 2007
I have a command line python app using poetry, that I would like to ship with a couple of jinja2 template files. As of know I have them in a template
directory. How would I go about shipping those templates with the app and how do I make sure that the app knows where the templates are located?
Here's my (naive) attempt at using pkgutil to accomplish this:
directory structure:
.
├── app.py
├── LICENSE
├── poetry.lock
├── pyproject.toml
└── templates
└── message.en_US.jinja2
app.py:
import pkgutil
from jinja2 import Environment, FileSystemLoader
data = pkgutil.get_data(__name__, "templates")
env = Environment(loader=FileSystemLoader(data))
template = env.get_template("message.en_US.jinja2")
print(template.render({"foo": 1, "bar": 2}))
pyproject.toml:
[tool.poetry]
name = "app"
version = "0.1.0"
description = "Does stuff"
authors = ["Foo Bar <[email protected]>"]
license = "AGPL-3.0-or-later"
[tool.poetry.dependencies]
python = "^3.8"
jinja2 = "^2.11.3"
[tool.poetry.scripts]
app = "app:main"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
This fails because the templates folder doesn't get packaged. I also don't know if I can pass the folder to the Environment
constructor like this.
Upvotes: 3
Views: 4469
Reputation: 339
Poetry provides a fairly simple but non-obvious solution (tucked away): pyproject.toml - [poetry.tool]include = [...]
[tool.poetry]
...
include = ["resource/resource.txt"]
Upvotes: 3
Reputation: 22398
In the context of Jinja this can be done easily with PackageLoader
, which is able to load resources from a Python import package directly.
And of course make sure the resource files (the template files) are correctly "packaged": the files should be part of an import package. In the case of poetry, make sure to have the correct values for the include
and packages
fields in your pyproject.toml
.
Upvotes: 2