{"id":"e29d1d4a19dc69f0","repo":"sqlalchemy/alembic","slug":"template-rendering-failed-see-s-for-a-template-o","errorCode":null,"errorMessage":"Template rendering failed; see %s for a template-oriented traceback.","messagePattern":"Template rendering failed; see (.+?) for a template-oriented traceback\\.","errorType":"exception","errorClass":"CommandError","httpStatus":null,"severity":"error","filePath":"alembic/util/pyfiles.py","lineNumber":41,"sourceCode":"    template_file: str | os.PathLike[str],\n    dest: str | os.PathLike[str],\n    output_encoding: str,\n    *,\n    append_with_newlines: bool = False,\n    **kw: Any,\n) -> None:\n    template = Template(filename=_preserving_path_as_str(template_file))\n    try:\n        output = template.render_unicode(**kw).encode(output_encoding)\n    except:\n        with tempfile.NamedTemporaryFile(suffix=\".txt\", delete=False) as ntf:\n            ntf.write(\n                exceptions.text_error_template()\n                .render_unicode()\n                .encode(output_encoding)\n            )\n            fname = ntf.name\n        raise CommandError(\n            \"Template rendering failed; see %s for a \"\n            \"template-oriented traceback.\" % fname\n        )\n    else:\n        with open(dest, \"ab\" if append_with_newlines else \"wb\") as f:\n            if append_with_newlines:\n                f.write(\"\\n\\n\".encode(output_encoding))\n            f.write(output)\n\n\ndef coerce_resource_to_filename(fname_or_resource: str) -> pathlib.Path:\n    \"\"\"Interpret a filename as either a filesystem location or as a package\n    resource.\n\n    Names that are non absolute paths and contain a colon\n    are interpreted as resources and coerced to a file location.\n\n    \"\"\"","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/sqlalchemy/alembic/blob/44fb3450330204b222ff05135e1fbbbdb28c44db/alembic/util/pyfiles.py#L23-L59","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before: script.py.mako references undefined 'user' variable\n## ${user}\nrevision = ${repr(up_revision)}\n\n# after: remove undefined variable, use only provided context\n## autogenerated\nrevision = ${repr(up_revision)}\ndown_revision = ${repr(down_revision)}","handlingStrategy":"try-catch","validationCode":"from pathlib import Path\nfrom mako.template import Template\n\ndef validate_template(template_path: str, **ctx):\n    t = Template(filename=template_path)\n    try:\n        t.render_unicode(**ctx)\n    except Exception as e:\n        raise ValueError(f'Template {template_path} would fail: {e}') from e\n\nvalidate_template('alembic/script.py.mako', up_revision='x', down_revision=None,\n                  branch_labels=None, depends_on=None)","typeGuard":null,"tryCatchPattern":"from alembic.util.exc import CommandError\ntry:\n    command.revision(cfg, message='msg')\nexcept CommandError as e:\n    if 'Template rendering failed' in str(e):\n        path = str(e).split('see ')[-1].rstrip('.')\n        print(f'Open {path} for the Mako traceback; fix script.py.mako and retry.')\n    else:\n        raise","preventionTips":["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."],"tags":["alembic","mako","template","migration-generation","command"],"analyzedSha":"44fb3450330204b222ff05135e1fbbbdb28c44db","analyzedAt":"2026-08-04T19:57:10.248Z","schemaVersion":2}