私は、Jinja2を使ってテンプレートをレンダリングすることによってSQLクエリの作成と実行を処理するモジュールを持っています。モジュール自体と「テンプレート」というディレクトリは、ネットワーク上の複数のマシンからアクセスできるネットワークドライブ上にあります。Jinja2は、作業ディレクトリとは別の場所からテンプレートをロードします。
期待どおり、同じディレクトリ内で作業するとすべて機能します。
このモジュールを別の場所からロードして使用しようとすると、TemplateNotFound:
エラーが発生します。私はFileSystemLoader
関数を呼び出すとき、それは検索だと思う
env = Environment(loader=FileSystemLoader('templates'))
:
from jinja2 import Environment, FileSystemLoader, Template, meta
def get_sql_query(position):
filename = "PositionDelta.sqltemplate"
# Create Jinja2 Environment, using the 'templates' folder
Error here --> env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template(filename)
# Get Source of template file
template_source = env.loader.get_source(env, filename)[0]
# Parse template source and get all undeclared variables
parsed_content = env.parse(template_source)
template_variables = list(meta.find_undeclared_variables(parsed_content))
# Get all tag values associated with position
tag_values = get_tags_list(position)
# Combine template variables and tag values into dictionary and render sql query from template
dictionary = dict(zip(template_variables, tag_values))
sql_query = template.render(dictionary)
return sql_query
失敗している。この関数は次の行です:関数自体は、エラーを含む行が強調表示して、次のようになりますテンプレートフォルダの作業フォルダに対する相対パス。モジュールの場所自体に関連するテンプレートディレクトリを探すように設定するにはどうすればよいですか?
これは、いくつかの理由から、 1. LinuxとWindowsマシンからテンプレートディレクトリにアクセスする必要があります。私は両方の場合にif文をそこに置くことができます。 2.モジュールをオフラインで作業したい、ネットワークにアクセスできない場合のために同僚と共有したい。代わりに、私はすべてのモジュールをパッケージに集め、jinja.PackageLoader()を使用しました - 答えを参照してください – cbcoutinho