Skip to content

Commit

Permalink
feat: allow views to manually specify their url pattern and name
Browse files Browse the repository at this point in the history
  • Loading branch information
jerivas committed Feb 23, 2022
1 parent e87ae79 commit d5edf7a
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions file_router/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import re
from importlib import import_module

from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.template import RequestContext, Template
from django.urls import path
Expand All @@ -12,9 +11,10 @@
DISALLOWED_CHARS = re.compile(
"|".join(
[
r"^-", # Dash at the start
r"^-+", # Leading dashes
r"[<>]", # Angle brackets (url param wrapper)
r"\w+\:", # Letters followed by colon (path converters)
r"-+$", # Trailing dashes
]
)
)
Expand All @@ -35,20 +35,25 @@ def file_patterns(start_dir, append_slash=False):
for file in files:
if not file.endswith(".py"):
continue

module_path = f"{root}/{file}".replace(".py", "").replace("/", ".")
try:
module = import_module(module_path)
except ImportError as exc:
raise ImproperlyConfigured(
f"Failed to import {module_path}. Ensure it's a valid Python file."
) from exc
module = import_module(module_path)
view_fn = getattr(module, "view", None)
if not callable(view_fn):
continue
url = "" if file == "index.py" else file.replace(".py", "")
url = start_dir_re.sub("", f"{root}/{url}").strip("/")
url = (url + "/") if append_slash else url
urlname = DISALLOWED_CHARS.sub("", TO_DASHES.sub("-", url))

try:
url = view_fn.url
except AttributeError:
url = "" if file == "index.py" else file.replace(".py", "")
url = start_dir_re.sub("", f"{root}/{url}").strip("/")
url = (url + "/") if append_slash else url

try:
urlname = view_fn.urlname
except AttributeError:
urlname = DISALLOWED_CHARS.sub("", TO_DASHES.sub("-", url))

patterns.append(path(url, view_fn, name=urlname))
return patterns

Expand Down

0 comments on commit d5edf7a

Please sign in to comment.