Skip to content

Commit d5edf7a

Browse files
committed
feat: allow views to manually specify their url pattern and name
1 parent e87ae79 commit d5edf7a

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

file_router/__init__.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import re
33
from importlib import import_module
44

5-
from django.core.exceptions import ImproperlyConfigured
65
from django.http import HttpResponse
76
from django.template import RequestContext, Template
87
from django.urls import path
@@ -12,9 +11,10 @@
1211
DISALLOWED_CHARS = re.compile(
1312
"|".join(
1413
[
15-
r"^-", # Dash at the start
14+
r"^-+", # Leading dashes
1615
r"[<>]", # Angle brackets (url param wrapper)
1716
r"\w+\:", # Letters followed by colon (path converters)
17+
r"-+$", # Trailing dashes
1818
]
1919
)
2020
)
@@ -35,20 +35,25 @@ def file_patterns(start_dir, append_slash=False):
3535
for file in files:
3636
if not file.endswith(".py"):
3737
continue
38+
3839
module_path = f"{root}/{file}".replace(".py", "").replace("/", ".")
39-
try:
40-
module = import_module(module_path)
41-
except ImportError as exc:
42-
raise ImproperlyConfigured(
43-
f"Failed to import {module_path}. Ensure it's a valid Python file."
44-
) from exc
40+
module = import_module(module_path)
4541
view_fn = getattr(module, "view", None)
4642
if not callable(view_fn):
4743
continue
48-
url = "" if file == "index.py" else file.replace(".py", "")
49-
url = start_dir_re.sub("", f"{root}/{url}").strip("/")
50-
url = (url + "/") if append_slash else url
51-
urlname = DISALLOWED_CHARS.sub("", TO_DASHES.sub("-", url))
44+
45+
try:
46+
url = view_fn.url
47+
except AttributeError:
48+
url = "" if file == "index.py" else file.replace(".py", "")
49+
url = start_dir_re.sub("", f"{root}/{url}").strip("/")
50+
url = (url + "/") if append_slash else url
51+
52+
try:
53+
urlname = view_fn.urlname
54+
except AttributeError:
55+
urlname = DISALLOWED_CHARS.sub("", TO_DASHES.sub("-", url))
56+
5257
patterns.append(path(url, view_fn, name=urlname))
5358
return patterns
5459

0 commit comments

Comments
 (0)