Pages
1from plain.http import Http404, ResponsePermanentRedirect, ResponseRedirect
2from plain.utils.functional import cached_property
3from plain.views import TemplateView
4
5from .exceptions import PageNotFoundError, RedirectPageError
6from .registry import registry
7
8
9class PageView(TemplateView):
10 template_name = "page.html"
11
12 @cached_property
13 def page(self):
14 # Passed manually by the kwargs in the path definition
15 url_path = self.url_kwargs.get("url_path", "index")
16
17 try:
18 return registry.get_page(url_path)
19 except PageNotFoundError:
20 raise Http404()
21
22 def get_template_names(self) -> list[str]:
23 """
24 Allow for more specific user templates like
25 markdown.html or html.html
26 """
27 return [self.page.get_template_name()] + super().get_template_names()
28
29 def get_template_context(self):
30 context = super().get_template_context()
31 context["page"] = self.page
32 return context
33
34 def get(self):
35 if self.page.content_type == "redirect":
36 url = self.page.vars.get("url")
37
38 if not url:
39 raise RedirectPageError(
40 f"Redirect page {self.page.url_path} is missing a url"
41 )
42
43 if self.page.vars.get("temporary", True):
44 return ResponseRedirect(url)
45 else:
46 return ResponsePermanentRedirect(url)
47
48 return super().get()