plain 0.56.1__py3-none-any.whl → 0.58.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plain/exceptions.py CHANGED
@@ -6,6 +6,23 @@ import operator
6
6
 
7
7
  from plain.utils.hashable import make_hashable
8
8
 
9
+ # MARK: Configuration and Registry
10
+
11
+
12
+ class PackageRegistryNotReady(Exception):
13
+ """The plain.packages registry is not populated yet"""
14
+
15
+ pass
16
+
17
+
18
+ class ImproperlyConfigured(Exception):
19
+ """Plain is somehow improperly configured"""
20
+
21
+ pass
22
+
23
+
24
+ # MARK: Model and Field Errors
25
+
9
26
 
10
27
  class FieldDoesNotExist(Exception):
11
28
  """The requested model field does not exist"""
@@ -13,8 +30,8 @@ class FieldDoesNotExist(Exception):
13
30
  pass
14
31
 
15
32
 
16
- class PackageRegistryNotReady(Exception):
17
- """The plain.packages registry is not populated yet"""
33
+ class FieldError(Exception):
34
+ """Some kind of problem with a model field."""
18
35
 
19
36
  pass
20
37
 
@@ -31,6 +48,9 @@ class MultipleObjectsReturned(Exception):
31
48
  pass
32
49
 
33
50
 
51
+ # MARK: Security and Suspicious Operations
52
+
53
+
34
54
  class SuspiciousOperation(Exception):
35
55
  """The user did something suspicious"""
36
56
 
@@ -53,12 +73,6 @@ class DisallowedHost(SuspiciousOperation):
53
73
  pass
54
74
 
55
75
 
56
- class DisallowedRedirect(SuspiciousOperation):
57
- """Redirect to scheme not in allowed list"""
58
-
59
- pass
60
-
61
-
62
76
  class TooManyFieldsSent(SuspiciousOperation):
63
77
  """
64
78
  The number of fields in a GET or POST request exceeded
@@ -86,6 +100,9 @@ class RequestDataTooBig(SuspiciousOperation):
86
100
  pass
87
101
 
88
102
 
103
+ # MARK: HTTP and Request Errors
104
+
105
+
89
106
  class BadRequest(Exception):
90
107
  """The request is malformed and cannot be processed."""
91
108
 
@@ -98,17 +115,7 @@ class PermissionDenied(Exception):
98
115
  pass
99
116
 
100
117
 
101
- class ImproperlyConfigured(Exception):
102
- """Plain is somehow improperly configured"""
103
-
104
- pass
105
-
106
-
107
- class FieldError(Exception):
108
- """Some kind of problem with a model field."""
109
-
110
- pass
111
-
118
+ # MARK: Validation
112
119
 
113
120
  NON_FIELD_ERRORS = "__all__"
114
121
 
@@ -211,6 +218,9 @@ class ValidationError(Exception):
211
218
  return hash(tuple(sorted(self.error_list, key=operator.attrgetter("message"))))
212
219
 
213
220
 
221
+ # MARK: Database
222
+
223
+
214
224
  class EmptyResultSet(Exception):
215
225
  """A database query predicate is impossible."""
216
226
 
plain/forms/README.md CHANGED
@@ -33,8 +33,6 @@ Then in your template, you can render the form fields.
33
33
  {% block content %}
34
34
 
35
35
  <form method="post">
36
- {{ csrf_input }}
37
-
38
36
  <!-- Render general form errors -->
39
37
  {% for error in form.non_field_errors %}
40
38
  <div>{{ error }}</div>
plain/http/__init__.py CHANGED
@@ -19,7 +19,6 @@ from plain.http.response import (
19
19
  ResponseNotAllowed,
20
20
  ResponseNotFound,
21
21
  ResponseNotModified,
22
- ResponsePermanentRedirect,
23
22
  ResponseRedirect,
24
23
  ResponseServerError,
25
24
  StreamingResponse,
@@ -36,7 +35,6 @@ __all__ = [
36
35
  "ResponseBase",
37
36
  "StreamingResponse",
38
37
  "ResponseRedirect",
39
- "ResponsePermanentRedirect",
40
38
  "ResponseNotModified",
41
39
  "ResponseBadRequest",
42
40
  "ResponseForbidden",
plain/http/response.py CHANGED
@@ -10,10 +10,8 @@ from email.header import Header
10
10
  from functools import cached_property
11
11
  from http.client import responses
12
12
  from http.cookies import SimpleCookie
13
- from urllib.parse import urlparse
14
13
 
15
14
  from plain import signals
16
- from plain.exceptions import DisallowedRedirect
17
15
  from plain.http.cookie import sign_cookie_value
18
16
  from plain.json import PlainJSONEncoder
19
17
  from plain.runtime import settings
@@ -566,19 +564,18 @@ class FileResponse(StreamingResponse):
566
564
  self.headers["Content-Disposition"] = content_disposition
567
565
 
568
566
 
569
- class ResponseRedirectBase(Response):
570
- allowed_schemes = ["http", "https", "ftp"]
567
+ class ResponseRedirect(Response):
568
+ """HTTP redirect response"""
569
+
570
+ status_code = 302
571
571
 
572
572
  def __init__(self, redirect_to, **kwargs):
573
573
  super().__init__(**kwargs)
574
574
  self.headers["Location"] = iri_to_uri(redirect_to)
575
- parsed = urlparse(str(redirect_to))
576
- if parsed.scheme and parsed.scheme not in self.allowed_schemes:
577
- raise DisallowedRedirect(
578
- f"Unsafe redirect to URL with protocol '{parsed.scheme}'"
579
- )
580
575
 
581
- url = property(lambda self: self.headers["Location"])
576
+ @property
577
+ def url(self):
578
+ return self.headers["Location"]
582
579
 
583
580
  def __repr__(self):
584
581
  return (
@@ -592,18 +589,6 @@ class ResponseRedirectBase(Response):
592
589
  )
593
590
 
594
591
 
595
- class ResponseRedirect(ResponseRedirectBase):
596
- """HTTP 302 response"""
597
-
598
- status_code = 302
599
-
600
-
601
- class ResponsePermanentRedirect(ResponseRedirectBase):
602
- """HTTP 301 response"""
603
-
604
- status_code = 301
605
-
606
-
607
592
  class ResponseNotModified(Response):
608
593
  """HTTP 304 response"""
609
594
 
@@ -1,6 +1,6 @@
1
1
  import re
2
2
 
3
- from plain.http import ResponsePermanentRedirect
3
+ from plain.http import ResponseRedirect
4
4
  from plain.runtime import settings
5
5
 
6
6
 
@@ -12,7 +12,7 @@ class HttpsRedirectMiddleware:
12
12
  self.https_redirect_enabled = settings.HTTPS_REDIRECT_ENABLED
13
13
  self.https_redirect_host = settings.HTTPS_REDIRECT_HOST
14
14
  self.https_redirect_exempt = [
15
- re.compile(r) for r in settings.HTTPS_REDIRECT_EXEMPT
15
+ re.compile(r) for r in settings.HTTPS_REDIRECT_EXEMPT_PATHS
16
16
  ]
17
17
 
18
18
  def __call__(self, request):
@@ -26,11 +26,15 @@ class HttpsRedirectMiddleware:
26
26
  return self.get_response(request)
27
27
 
28
28
  def maybe_https_redirect(self, request):
29
- path = request.path.lstrip("/")
30
29
  if (
31
30
  self.https_redirect_enabled
32
31
  and not request.is_https()
33
- and not any(pattern.search(path) for pattern in self.https_redirect_exempt)
32
+ and not any(
33
+ pattern.search(request.path_info)
34
+ for pattern in self.https_redirect_exempt
35
+ )
34
36
  ):
35
37
  host = self.https_redirect_host or request.get_host()
36
- return ResponsePermanentRedirect(f"https://{host}{request.get_full_path()}")
38
+ return ResponseRedirect(
39
+ f"https://{host}{request.get_full_path()}", status_code=301
40
+ )
@@ -1,4 +1,4 @@
1
- from plain.http import ResponsePermanentRedirect
1
+ from plain.http import ResponseRedirect
2
2
  from plain.runtime import settings
3
3
  from plain.urls import Resolver404, get_resolver
4
4
  from plain.utils.http import escape_leading_slashes
@@ -22,7 +22,9 @@ class RedirectSlashMiddleware:
22
22
  # If the given URL is "Not Found", then check if we should redirect to
23
23
  # a path with a slash appended.
24
24
  if response.status_code == 404 and self.should_redirect_with_slash(request):
25
- return ResponsePermanentRedirect(self.get_full_path_with_slash(request))
25
+ return ResponseRedirect(
26
+ self.get_full_path_with_slash(request), status_code=301
27
+ )
26
28
 
27
29
  return response
28
30
 
@@ -3,31 +3,20 @@ Default Plain settings. Override these with settings in the module pointed to
3
3
  by the PLAIN_SETTINGS_MODULE environment variable.
4
4
  """
5
5
 
6
- ####################
7
- # CORE #
8
- ####################
6
+ # MARK: Core Settings
9
7
 
10
8
  DEBUG: bool = False
11
9
 
12
- # Hosts/domain names that are valid for this site.
13
- # "*" matches anything, ".example.com" matches example.com and all subdomains
14
- ALLOWED_HOSTS: list[str] = []
15
-
16
- # Local time zone for this installation. All choices can be found here:
17
- # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
18
- # systems may support all possibilities). This is interpreted as the default
19
- # user time zone.
20
- TIME_ZONE: str = "UTC"
21
-
22
- # Default charset to use for all Response objects, if a MIME type isn't
23
- # manually specified. It's used to construct the Content-Type header.
24
- DEFAULT_CHARSET = "utf-8"
25
-
26
10
  # List of strings representing installed packages.
27
11
  INSTALLED_PACKAGES: list[str] = []
28
12
 
29
- # Whether to append trailing slashes to URLs.
30
- APPEND_SLASH = True
13
+ URLS_ROUTER: str
14
+
15
+ # MARK: HTTP and Security
16
+
17
+ # Hosts/domain names that are valid for this site.
18
+ # "*" matches anything, ".example.com" matches example.com and all subdomains
19
+ ALLOWED_HOSTS: list[str] = []
31
20
 
32
21
  # Default headers for all responses.
33
22
  DEFAULT_RESPONSE_HEADERS = {
@@ -42,7 +31,13 @@ DEFAULT_RESPONSE_HEADERS = {
42
31
 
43
32
  # Whether to redirect all non-HTTPS requests to HTTPS.
44
33
  HTTPS_REDIRECT_ENABLED = True
45
- HTTPS_REDIRECT_EXEMPT = []
34
+
35
+ # Regex patterns for paths that should be exempt from HTTPS redirect
36
+ # Examples: [r"^/health$", r"/api/internal/.*", r"/dev/.*"]
37
+ HTTPS_REDIRECT_EXEMPT_PATHS: list[str] = []
38
+
39
+ # Custom host to redirect to for HTTPS. If None, uses the same host as the request.
40
+ # Useful for redirecting to a different domain (e.g., "secure.example.com")
46
41
  HTTPS_REDIRECT_HOST = None
47
42
 
48
43
  # If your Plain app is behind a proxy that sets a header to specify secure
@@ -68,7 +63,24 @@ SECRET_KEY: str
68
63
  # secret key rotation.
69
64
  SECRET_KEY_FALLBACKS: list[str] = []
70
65
 
71
- URLS_ROUTER: str
66
+ # MARK: Internationalization
67
+
68
+ # Local time zone for this installation. All choices can be found here:
69
+ # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
70
+ # systems may support all possibilities). This is interpreted as the default
71
+ # user time zone.
72
+ TIME_ZONE: str = "UTC"
73
+
74
+ # Default charset to use for all Response objects, if a MIME type isn't
75
+ # manually specified. It's used to construct the Content-Type header.
76
+ DEFAULT_CHARSET = "utf-8"
77
+
78
+ # MARK: URL Configuration
79
+
80
+ # Whether to append trailing slashes to URLs.
81
+ APPEND_SLASH = True
82
+
83
+ # MARK: File Uploads
72
84
 
73
85
  # List of upload handler classes to be applied in order.
74
86
  FILE_UPLOAD_HANDLERS = [
@@ -100,41 +112,30 @@ FILE_UPLOAD_TEMP_DIR = None
100
112
  # User-defined overrides for error views by status code
101
113
  HTTP_ERROR_VIEWS: dict[int] = {}
102
114
 
103
- ##############
104
- # MIDDLEWARE #
105
- ##############
115
+ # MARK: Middleware
106
116
 
107
117
  # List of middleware to use. Order is important; in the request phase, these
108
118
  # middleware will be applied in the order given, and in the response
109
119
  # phase the middleware will be applied in reverse order.
110
120
  MIDDLEWARE: list[str] = []
111
121
 
112
- ########
113
- # CSRF #
114
- ########
115
-
116
- # Settings for CSRF cookie.
117
- CSRF_COOKIE_NAME = "csrftoken"
118
- CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 # 1 year
119
- CSRF_COOKIE_DOMAIN = None
120
- CSRF_COOKIE_PATH = "/"
121
- CSRF_COOKIE_SECURE = True
122
- CSRF_COOKIE_HTTPONLY = False
123
- CSRF_COOKIE_SAMESITE = "Lax"
124
- CSRF_HEADER_NAME = "CSRF-Token"
125
- CSRF_FIELD_NAME = "_csrftoken"
122
+ # MARK: CSRF
123
+
124
+ # A list of trusted origins for unsafe (POST/PUT/DELETE etc.) requests.
125
+ # These origins will be allowed regardless of the normal CSRF checks.
126
+ # Each origin should be a full origin like "https://example.com" or "https://sub.example.com:8080"
126
127
  CSRF_TRUSTED_ORIGINS: list[str] = []
127
128
 
128
- ###########
129
- # LOGGING #
130
- ###########
129
+ # Regex patterns for paths that should be exempt from CSRF protection
130
+ # Examples: [r"^/api/", r"/webhooks/.*", r"/health$"]
131
+ CSRF_EXEMPT_PATHS: list[str] = []
132
+
133
+ # MARK: Logging
131
134
 
132
135
  # Custom logging configuration.
133
136
  LOGGING = {}
134
137
 
135
- ###############
136
- # ASSETS #
137
- ###############
138
+ # MARK: Assets
138
139
 
139
140
  # Whether to redirect the original asset path to the fingerprinted path.
140
141
  ASSETS_REDIRECT_ORIGINAL = True
@@ -143,9 +144,7 @@ ASSETS_REDIRECT_ORIGINAL = True
143
144
  # Ex. "https://cdn.example.com/assets/"
144
145
  ASSETS_BASE_URL: str = ""
145
146
 
146
- ####################
147
- # PREFLIGHT CHECKS #
148
- ####################
147
+ # MARK: Preflight Checks
149
148
 
150
149
  # List of all issues generated by system checks that should be silenced. Light
151
150
  # issues like warnings, infos or debugs will not generate a message. Silencing
@@ -153,14 +152,10 @@ ASSETS_BASE_URL: str = ""
153
152
  # message, but Plain will not stop you from e.g. running server.
154
153
  PREFLIGHT_SILENCED_CHECKS = []
155
154
 
156
- #############
157
- # Templates #
158
- #############
155
+ # MARK: Templates
159
156
 
160
157
  TEMPLATES_JINJA_ENVIRONMENT = "plain.templates.jinja.DefaultEnvironment"
161
158
 
162
- #########
163
- # Shell #
164
- #########
159
+ # MARK: Shell
165
160
 
166
161
  SHELL_IMPORT: str = ""
plain/templates/README.md CHANGED
@@ -70,7 +70,6 @@ class HTMXJSExtension(InclusionTagExtension):
70
70
 
71
71
  def get_context(self, context, *args, **kwargs):
72
72
  return {
73
- "csrf_token": context["csrf_token"],
74
73
  "DEBUG": settings.DEBUG,
75
74
  "extensions": kwargs.get("extensions", []),
76
75
  }
plain/test/client.py CHANGED
@@ -114,8 +114,7 @@ class ClientHandler(BaseHandler):
114
114
  the originating WSGIRequest attached to its ``wsgi_request`` attribute.
115
115
  """
116
116
 
117
- def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
118
- self.enforce_csrf_checks = enforce_csrf_checks
117
+ def __init__(self, *args, **kwargs):
119
118
  super().__init__(*args, **kwargs)
120
119
 
121
120
  def __call__(self, environ):
@@ -126,12 +125,6 @@ class ClientHandler(BaseHandler):
126
125
 
127
126
  request_started.send(sender=self.__class__, environ=environ)
128
127
  request = WSGIRequest(environ)
129
- # sneaky little hack so that we can easily get round
130
- # CsrfViewMiddleware. This makes life easier, and is probably
131
- # required for backwards compatibility with external tests against
132
- # admin views.
133
- if not self.enforce_csrf_checks:
134
- request.csrf_exempt = True
135
128
 
136
129
  # Request goes through middleware.
137
130
  response = self.get_response(request)
@@ -420,14 +413,13 @@ class Client(RequestFactory):
420
413
 
421
414
  def __init__(
422
415
  self,
423
- enforce_csrf_checks=False,
424
416
  raise_request_exception=True,
425
417
  *,
426
418
  headers=None,
427
419
  **defaults,
428
420
  ):
429
421
  super().__init__(headers=headers, **defaults)
430
- self.handler = ClientHandler(enforce_csrf_checks)
422
+ self.handler = ClientHandler()
431
423
  self.raise_request_exception = raise_request_exception
432
424
  self.exc_info = None
433
425
  self.extra = None
plain/views/README.md CHANGED
@@ -142,8 +142,6 @@ Rendering forms is done directly in the HTML.
142
142
  {% block content %}
143
143
 
144
144
  <form method="post">
145
- {{ csrf_input }}
146
-
147
145
  <!-- Render general form errors -->
148
146
  {% for error in form.non_field_errors %}
149
147
  <div>{{ error }}</div>
plain/views/redirect.py CHANGED
@@ -1,29 +1,29 @@
1
- import logging
2
-
3
- from plain.http import (
4
- ResponseGone,
5
- ResponsePermanentRedirect,
6
- ResponseRedirect,
7
- )
1
+ from plain.http import ResponseRedirect
8
2
  from plain.urls import reverse
9
3
 
10
4
  from .base import View
11
5
 
12
- logger = logging.getLogger("plain.request")
13
-
14
6
 
15
7
  class RedirectView(View):
16
8
  """Provide a redirect on any GET request."""
17
9
 
18
- permanent = False
10
+ status_code = 302
19
11
  url: str | None = None
20
- pattern_name: str | None = None
21
- query_string = False
12
+ url_name: str | None = None
13
+ preserve_query_params = False
22
14
 
23
- def __init__(self, url=None, permanent=None):
24
- # Allow url and permanent to be set in RedirectView.as_view(url="...", permanent=True)
15
+ def __init__(
16
+ self, url=None, status_code=None, url_name=None, preserve_query_params=None
17
+ ):
18
+ # Allow attributes to be set in RedirectView.as_view(url="...", status_code=301, etc.)
25
19
  self.url = url or self.url
26
- self.permanent = permanent if permanent is not None else self.permanent
20
+ self.status_code = status_code if status_code is not None else self.status_code
21
+ self.url_name = url_name or self.url_name
22
+ self.preserve_query_params = (
23
+ preserve_query_params
24
+ if preserve_query_params is not None
25
+ else self.preserve_query_params
26
+ )
27
27
 
28
28
  def get_redirect_url(self):
29
29
  """
@@ -33,30 +33,19 @@ class RedirectView(View):
33
33
  """
34
34
  if self.url:
35
35
  url = self.url % self.url_kwargs
36
- elif self.pattern_name:
37
- url = reverse(self.pattern_name, *self.url_args, **self.url_kwargs)
36
+ elif self.url_name:
37
+ url = reverse(self.url_name, *self.url_args, **self.url_kwargs)
38
38
  else:
39
- return None
39
+ raise ValueError("RedirectView requires either url or url_name to be set")
40
40
 
41
41
  args = self.request.meta.get("QUERY_STRING", "")
42
- if args and self.query_string:
42
+ if args and self.preserve_query_params:
43
43
  url = f"{url}?{args}"
44
44
  return url
45
45
 
46
46
  def get(self):
47
47
  url = self.get_redirect_url()
48
- if url:
49
- if self.permanent:
50
- return ResponsePermanentRedirect(url)
51
- else:
52
- return ResponseRedirect(url)
53
- else:
54
- logger.warning(
55
- "Gone: %s",
56
- self.request.path,
57
- extra={"status_code": 410, "request": self.request},
58
- )
59
- return ResponseGone()
48
+ return ResponseRedirect(url, status_code=self.status_code)
60
49
 
61
50
  def head(self):
62
51
  return self.get()
plain/views/templates.py CHANGED
@@ -1,27 +1,11 @@
1
- from plain.csrf.middleware import get_token
2
1
  from plain.exceptions import ImproperlyConfigured
3
2
  from plain.http import Response
4
3
  from plain.runtime import settings
5
4
  from plain.templates import Template, TemplateFileMissing
6
- from plain.utils.functional import lazy
7
- from plain.utils.html import format_html
8
- from plain.utils.safestring import SafeString
9
5
 
10
6
  from .base import View
11
7
 
12
8
 
13
- def csrf_input(request):
14
- return format_html(
15
- '<input type="hidden" name="{}" value="{}">',
16
- settings.CSRF_FIELD_NAME,
17
- get_token(request),
18
- )
19
-
20
-
21
- csrf_input_lazy = lazy(csrf_input, SafeString, str)
22
- csrf_token_lazy = lazy(get_token, str)
23
-
24
-
25
9
  class TemplateView(View):
26
10
  """
27
11
  Render a template.
@@ -37,8 +21,6 @@ class TemplateView(View):
37
21
  return {
38
22
  "request": self.request,
39
23
  "template_names": self.get_template_names(),
40
- "csrf_input": csrf_input_lazy(self.request),
41
- "csrf_token": csrf_token_lazy(self.request),
42
24
  "DEBUG": settings.DEBUG,
43
25
  }
44
26
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plain
3
- Version: 0.56.1
3
+ Version: 0.58.0
4
4
  Summary: A web framework for building products with Python.
5
5
  Author-email: Dave Gaeddert <dave.gaeddert@dropseed.dev>
6
6
  License-File: LICENSE