Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Allow -t/--template to take a path to a .tmpl file (#8071)

Adriana732b19a04f0
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rst
index c5ff19c26..32ae6173e 100644
--- a/docs/topics/commands.rst
+++ b/docs/topics/commands.rst
@@ -274,6 +274,9 @@ Your templates replace the built-in ones, which live in the :file:`templates`
directory of the ``scrapy`` package, so copy over any of those that you want to
keep.
+Alternatively, pass ``-t`` a path to a :file:`.tmpl` file instead of a name,
+to use it without touching :setting:`TEMPLATES_DIR`.
+
Templates are rendered with :class:`string.Template`: ``$variable`` and
``${variable}`` are replaced, and ``$$`` renders as a single ``$``, which
regular expressions often need. Rendering fails on any variable other than the
diff --git a/scrapy/commands/genspider.py b/scrapy/commands/genspider.py
index 52f9cd4b0..c32a01395 100644
--- a/scrapy/commands/genspider.py
+++ b/scrapy/commands/genspider.py
@@ -81,7 +81,7 @@ class Command(ScrapyCommand):
"--template",
dest="template",
default="basic",
- help="Uses a custom template.",
+ help="Uses a custom template, given by name or by path to a .tmpl file.",
)
parser.add_argument(
"--force",
@@ -171,9 +171,10 @@ class Command(ScrapyCommand):
return Path(spider_file)
def _find_template(self, template: str) -> Path | None:
- template_file = Path(self.templates_dir, f"{template}.tmpl")
- if template_file.exists():
- return template_file
+ filename = template if template.endswith(".tmpl") else f"{template}.tmpl"
+ for template_file in (Path(filename), Path(self.templates_dir, filename)):
+ if template_file.exists():
+ return template_file
print(
f"Unable to find template: {template}\n",
'Use "scrapy genspider --list" to see all available templates.',
diff --git a/tests/test_command_genspider.py b/tests/test_command_genspider.py
index ddf25af4c..6617f46d5 100644
--- a/tests/test_command_genspider.py
+++ b/tests/test_command_genspider.py
@@ -57,6 +57,31 @@ class TestGenspiderCommand(TestProjectBase):
modify_time_after = spfile.stat().st_mtime
assert modify_time_after == modify_time_before
+ @pytest.mark.parametrize("suffix", ["", ".tmpl"])
+ def test_custom_template_path(self, suffix: str, proj_path: Path) -> None:
+ template = proj_path / "custom.tmpl"
+ template.write_text(
+ 'import scrapy\n\n\nclass $classname(scrapy.Spider):\n name = "$name"\n',
+ encoding="utf-8",
+ )
+ spname = "test_spider"
+ spfile = proj_path / self.project_name / "spiders" / f"{spname}.py"
+ assert (
+ call(
+ "genspider",
+ "-t",
+ str(template)[: -len(".tmpl")] if suffix == "" else str(template),
+ spname,
+ "test.com",
+ cwd=proj_path,
+ )
+ == 0
+ )
+ assert spfile.exists()
+ assert "class TestSpiderSpider(scrapy.Spider):" in spfile.read_text(
+ encoding="utf-8"
+ )
+
def test_list(self, proj_path: Path) -> None:
assert call("genspider", "--list", cwd=proj_path) == 0