sqlalchemy/alembic · error · CommandError
Template rendering failed; see %s for a template-oriented tr
Error message
Template rendering failed; see %s for a template-oriented traceback.
What it means
Raised as CommandError in template_to_file (pyfiles.py:41) when a Mako template (used to generate migration scripts or other files) fails to render. The bare except captures the failure, writes a Mako-formatted traceback to a temp .txt file, then raises CommandError pointing at that file so the developer can read a template-oriented (not Python-oriented) traceback.
Source
Thrown at alembic/util/pyfiles.py:41
template_file: str | os.PathLike[str],
dest: str | os.PathLike[str],
output_encoding: str,
*,
append_with_newlines: bool = False,
**kw: Any,
) -> None:
template = Template(filename=_preserving_path_as_str(template_file))
try:
output = template.render_unicode(**kw).encode(output_encoding)
except:
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as ntf:
ntf.write(
exceptions.text_error_template()
.render_unicode()
.encode(output_encoding)
)
fname = ntf.name
raise CommandError(
"Template rendering failed; see %s for a "
"template-oriented traceback." % fname
)
else:
with open(dest, "ab" if append_with_newlines else "wb") as f:
if append_with_newlines:
f.write("\n\n".encode(output_encoding))
f.write(output)
def coerce_resource_to_filename(fname_or_resource: str) -> pathlib.Path:
"""Interpret a filename as either a filesystem location or as a package
resource.
Names that are non absolute paths and contain a colon
are interpreted as resources and coerced to a file location.
"""View on GitHub (pinned to 44fb345033)
Solutions
- Open the temp file path named in the error message — it contains a Mako-specific traceback pinpointing the template line.
- Validate your script.py.mako against the default template; restore known-good content and re-apply changes incrementally.
- Ensure all variables the template expects (e.g. revision, down_revision, branch_labels, depends_on) are provided.
- Run `alembic revision` with --verbose for additional context if the temp traceback is insufficient.
Example fix
# before: script.py.mako references undefined 'user' variable
## ${user}
revision = ${repr(up_revision)}
# after: remove undefined variable, use only provided context
## autogenerated
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)} Defensive patterns
Strategy: try-catch
Validate before calling
from pathlib import Path
from mako.template import Template
def validate_template(template_path: str, **ctx):
t = Template(filename=template_path)
try:
t.render_unicode(**ctx)
except Exception as e:
raise ValueError(f'Template {template_path} would fail: {e}') from e
validate_template('alembic/script.py.mako', up_revision='x', down_revision=None,
branch_labels=None, depends_on=None) Try / catch
from alembic.util.exc import CommandError
try:
command.revision(cfg, message='msg')
except CommandError as e:
if 'Template rendering failed' in str(e):
path = str(e).split('see ')[-1].rstrip('.')
print(f'Open {path} for the Mako traceback; fix script.py.mako and retry.')
else:
raise Prevention
- Keep script.py.mako close to the upstream default; diff before customizing.
- Provide all template-expected variables when calling template_to_file.
- Lint Mako templates in CI by rendering against sample context.
When it happens
Trigger: Running `alembic revision` (which renders script.py.mako) when the template references an undefined variable; passing incompatible kwargs to template_to_file; a malformed Mako template with syntax errors; a template that calls a helper not present in the render context.
Common situations: Customizing script.py.mako and introducing a syntax error or referencing an undefined variable; upgrading Alembic and the bundled template changed but a local override is stale; passing render kwargs whose names don't match the template's expected variables.
Related errors
- Error executing editor (%s)
- No suitable editor found. Please set the "EDITOR" or "VISUAL
- Can't drop table in batch mode
- Constraint must have a name
- No such constraint: '%s'
AI-assisted analysis of sqlalchemy/alembic@44fb345033 (2026-08-04).
Data as JSON: /data/errors/e29d1d4a19dc69f0.json.
Report an issue: GitHub.