spiderweb-framework 0.11.0__tar.gz → 1.0.0__tar.gz

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.
Files changed (40) hide show
  1. spiderweb_framework-1.0.0/LICENSE.txt +48 -0
  2. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/PKG-INFO +39 -25
  3. spiderweb_framework-1.0.0/README.md +78 -0
  4. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/pyproject.toml +1 -1
  5. spiderweb_framework-1.0.0/spiderweb/constants.py +27 -0
  6. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/exceptions.py +5 -1
  7. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/main.py +90 -26
  8. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/__init__.py +21 -3
  9. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/base.py +1 -1
  10. spiderweb_framework-1.0.0/spiderweb/middleware/cors.py +158 -0
  11. spiderweb_framework-1.0.0/spiderweb/middleware/csrf.py +138 -0
  12. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/request.py +13 -8
  13. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/response.py +13 -10
  14. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/routes.py +2 -2
  15. spiderweb_framework-1.0.0/spiderweb/server_checks.py +18 -0
  16. spiderweb_framework-1.0.0/spiderweb/tests/__init__.py +4 -0
  17. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/tests/helpers.py +6 -4
  18. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/tests/middleware.py +9 -2
  19. spiderweb_framework-1.0.0/spiderweb/tests/test_middleware.py +734 -0
  20. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/tests/test_responses.py +39 -34
  21. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/tests/test_variable_urls.py +12 -6
  22. spiderweb_framework-1.0.0/spiderweb/tests/views_for_tests.py +49 -0
  23. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/utils.py +44 -0
  24. spiderweb_framework-0.11.0/LICENSE.txt +0 -21
  25. spiderweb_framework-0.11.0/README.md +0 -64
  26. spiderweb_framework-0.11.0/spiderweb/constants.py +0 -10
  27. spiderweb_framework-0.11.0/spiderweb/middleware/csrf.py +0 -65
  28. spiderweb_framework-0.11.0/spiderweb/tests/__init__.py +0 -1
  29. spiderweb_framework-0.11.0/spiderweb/tests/test_middleware.py +0 -88
  30. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/__init__.py +0 -0
  31. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/converters.py +0 -0
  32. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/db.py +0 -0
  33. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/decorators.py +0 -0
  34. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/default_views.py +0 -0
  35. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/example_validator.py +0 -0
  36. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/local_server.py +0 -0
  37. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/pydantic.py +0 -0
  38. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/sessions.py +0 -0
  39. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/secrets.py +0 -0
  40. {spiderweb_framework-0.11.0 → spiderweb_framework-1.0.0}/spiderweb/tests/test.html +0 -0
@@ -0,0 +1,48 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Joe Kaufeld
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ Substantial portions of spiderweb/middleware/cors.py and docs/middleware/cors.md
26
+ are from django-cors-headers and are subject to the following license:
27
+
28
+ MIT License
29
+
30
+ Copyright (c) 2017 Otto Yiu (https://ottoyiu.com) and other contributors.
31
+
32
+ Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ of this software and associated documentation files (the "Software"), to deal
34
+ in the Software without restriction, including without limitation the rights
35
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ copies of the Software, and to permit persons to whom the Software is
37
+ furnished to do so, subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in all
40
+ copies or substantial portions of the Software.
41
+
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
48
+ SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: spiderweb-framework
3
- Version: 0.11.0
3
+ Version: 1.0.0
4
4
  Summary: A small web framework, just big enough for a spider.
5
5
  License: LICENSE.txt
6
6
  Author: Joe Kaufeld
@@ -12,8 +12,8 @@ Classifier: Intended Audience :: Developers
12
12
  Classifier: License :: Other/Proprietary License
13
13
  Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
15
  Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
19
19
  Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
@@ -28,6 +28,21 @@ Description-Content-Type: text/markdown
28
28
 
29
29
  # spiderweb
30
30
 
31
+ <p align="center">
32
+ <img
33
+ src="https://img.shields.io/pypi/v/spiderweb-framework.svg?style=for-the-badge"
34
+ alt="PyPI release version for Spiderweb"
35
+ />
36
+ <img
37
+ src="https://img.shields.io/badge/gitmoji-%20😜%20😍-FFDD67.svg?style=for-the-badge"
38
+ alt="Gitmoji"
39
+ />
40
+ <img
41
+ src="https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge"
42
+ alt="Code style: Black"
43
+ />
44
+ </p>
45
+
31
46
  As a professional web developer focusing on arcane uses of Django for arcane purposes, it occurred to me a little while ago that I didn't actually know how a web framework _worked_.
32
47
 
33
48
  So I built one.
@@ -54,6 +69,8 @@ if __name__ == "__main__":
54
69
  app.start()
55
70
  ```
56
71
 
72
+ ## [View the docs here!](https://itsthejoker.github.io/spiderweb/#/)
73
+
57
74
  My goal with this framework was to do three things:
58
75
 
59
76
  1. Learn a lot
@@ -62,31 +79,28 @@ My goal with this framework was to do three things:
62
79
 
63
80
  And, honestly, I think I got there. Here's a non-exhaustive list of things this can do:
64
81
 
65
- * Function-based views
66
- * Optional Flask-style URL routing
67
- * Optional Django-style URL routing
68
- * URLs with variables in them a lá Django
69
- * Gunicorn support
70
- * Full middleware implementation
71
- * Limit routes by HTTP verbs
72
- * Custom error routes
73
- * Built-in dev server
74
- * HTML templates with Jinja2
75
- * Static files support
76
- * Cookies (reading and setting)
77
- * Optional append_slash (with automatic redirects!)
78
- * ~~CSRF middleware implementation~~ (it's there, but it's crappy and unsafe. I'm working on it.)
79
- * Optional POST data validation middleware with Pydantic
80
- * Database support (using Peewee, but the end user can use whatever they want as long as there's a Peewee driver for it)
81
- * Session middleware
82
-
83
- The TODO list:
84
-
85
- * Tests (important)
86
- * Fix CSRF middleware
82
+ - Function-based views
83
+ - Optional Flask-style URL routing
84
+ - Optional Django-style URL routing
85
+ - URLs with variables in them a lá Django
86
+ - Full middleware implementation
87
+ - Limit routes by HTTP verbs
88
+ - Custom error routes
89
+ - Built-in dev server
90
+ - Gunicorn support
91
+ - HTML templates with Jinja2
92
+ - Static files support
93
+ - Cookies (reading and setting)
94
+ - Optional append_slash (with automatic redirects!)
95
+ - CSRF middleware
96
+ - CORS middleware
97
+ - Optional POST data validation middleware with Pydantic
98
+ - Session middleware with built-in session store
99
+ - Database support (using Peewee, but you can use whatever you want as long as there's a Peewee driver for it)
100
+ - Tests (currently a little over 80% coverage)
87
101
 
88
102
  Once tests are in and proven to work, then I'll release as version 1.0.
89
103
 
90
- More documentation to follow!
104
+ - currently missing tests for cors middleware
91
105
 
92
106
  If you're reading this on GitHub, this repository is a public mirror of https://git.joekaufeld.com/jkaufeld/spiderweb.
@@ -0,0 +1,78 @@
1
+ # spiderweb
2
+
3
+ <p align="center">
4
+ <img
5
+ src="https://img.shields.io/pypi/v/spiderweb-framework.svg?style=for-the-badge"
6
+ alt="PyPI release version for Spiderweb"
7
+ />
8
+ <img
9
+ src="https://img.shields.io/badge/gitmoji-%20😜%20😍-FFDD67.svg?style=for-the-badge"
10
+ alt="Gitmoji"
11
+ />
12
+ <img
13
+ src="https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge"
14
+ alt="Code style: Black"
15
+ />
16
+ </p>
17
+
18
+ As a professional web developer focusing on arcane uses of Django for arcane purposes, it occurred to me a little while ago that I didn't actually know how a web framework _worked_.
19
+
20
+ So I built one.
21
+
22
+ `spiderweb` is a small web framework, just big enough to hold a spider. Getting started is easy:
23
+
24
+ ```shell
25
+ poetry add spiderweb-framework
26
+ ```
27
+
28
+ Create a new file and drop this in it:
29
+
30
+ ```python
31
+ from spiderweb import SpiderwebRouter
32
+ from spiderweb.response import HttpResponse
33
+
34
+ app = SpiderwebRouter()
35
+
36
+ @app.route("/")
37
+ def index(request):
38
+ return HttpResponse("HELLO, WORLD!")
39
+
40
+ if __name__ == "__main__":
41
+ app.start()
42
+ ```
43
+
44
+ ## [View the docs here!](https://itsthejoker.github.io/spiderweb/#/)
45
+
46
+ My goal with this framework was to do three things:
47
+
48
+ 1. Learn a lot
49
+ 2. Create an unholy blend of Django and Flask
50
+ 3. Not look at any existing code. Go off of vibes alone and try to solve all the problems I could think of in my own way
51
+
52
+ And, honestly, I think I got there. Here's a non-exhaustive list of things this can do:
53
+
54
+ - Function-based views
55
+ - Optional Flask-style URL routing
56
+ - Optional Django-style URL routing
57
+ - URLs with variables in them a lá Django
58
+ - Full middleware implementation
59
+ - Limit routes by HTTP verbs
60
+ - Custom error routes
61
+ - Built-in dev server
62
+ - Gunicorn support
63
+ - HTML templates with Jinja2
64
+ - Static files support
65
+ - Cookies (reading and setting)
66
+ - Optional append_slash (with automatic redirects!)
67
+ - CSRF middleware
68
+ - CORS middleware
69
+ - Optional POST data validation middleware with Pydantic
70
+ - Session middleware with built-in session store
71
+ - Database support (using Peewee, but you can use whatever you want as long as there's a Peewee driver for it)
72
+ - Tests (currently a little over 80% coverage)
73
+
74
+ Once tests are in and proven to work, then I'll release as version 1.0.
75
+
76
+ - currently missing tests for cors middleware
77
+
78
+ If you're reading this on GitHub, this repository is a public mirror of https://git.joekaufeld.com/jkaufeld/spiderweb.
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "spiderweb-framework"
3
- version = "0.11.0"
3
+ version = "1.0.0"
4
4
  description = "A small web framework, just big enough for a spider."
5
5
  authors = ["Joe Kaufeld <opensource@joekaufeld.com>"]
6
6
  readme = "README.md"
@@ -0,0 +1,27 @@
1
+ from peewee import DatabaseProxy
2
+
3
+ DEFAULT_ALLOWED_METHODS = ["POST", "GET", "PUT", "PATCH", "DELETE"]
4
+ DEFAULT_ENCODING = "UTF-8"
5
+ __version__ = "1.0.0"
6
+
7
+ # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
8
+ REGEX_COOKIE_NAME = r"^[a-zA-Z0-9\s\(\)<>@,;:\/\\\[\]\?=\{\}\"\t]*$"
9
+
10
+ DATABASE_PROXY = DatabaseProxy()
11
+
12
+ DEFAULT_CORS_ALLOW_METHODS = (
13
+ "DELETE",
14
+ "GET",
15
+ "OPTIONS",
16
+ "PATCH",
17
+ "POST",
18
+ "PUT",
19
+ )
20
+ DEFAULT_CORS_ALLOW_HEADERS = (
21
+ "accept",
22
+ "authorization",
23
+ "content-type",
24
+ "user-agent",
25
+ "x-csrftoken",
26
+ "x-requested-with",
27
+ )
@@ -5,7 +5,7 @@ class SpiderwebException(Exception):
5
5
  msg = self.args[0] if len(self.args) > 0 else ""
6
6
  if msg:
7
7
  return f"{name}() - {msg}"
8
- return f"{self.__class__.__name__}()"
8
+ return f"{name}()"
9
9
 
10
10
 
11
11
  class SpiderwebNetworkException(SpiderwebException):
@@ -86,3 +86,7 @@ class UnusedMiddleware(SpiderwebException):
86
86
 
87
87
  class NoResponseError(SpiderwebException):
88
88
  pass
89
+
90
+
91
+ class StartupErrors(ExceptionGroup):
92
+ pass
@@ -1,16 +1,22 @@
1
1
  import inspect
2
2
  import logging
3
3
  import pathlib
4
+ import re
4
5
  import traceback
5
6
  import urllib.parse as urlparse
7
+ from logging import Logger
6
8
  from threading import Thread
7
- from typing import Optional, Callable
9
+ from typing import Optional, Callable, Sequence, LiteralString, Literal
8
10
  from wsgiref.simple_server import WSGIServer
9
11
 
10
12
  from jinja2 import BaseLoader, Environment, FileSystemLoader
11
13
  from peewee import Database, SqliteDatabase
12
14
 
13
15
  from spiderweb.middleware import MiddlewareMixin
16
+ from spiderweb.constants import (
17
+ DEFAULT_CORS_ALLOW_METHODS,
18
+ DEFAULT_CORS_ALLOW_HEADERS,
19
+ )
14
20
  from spiderweb.constants import (
15
21
  DATABASE_PROXY,
16
22
  DEFAULT_ENCODING,
@@ -30,9 +36,9 @@ from spiderweb.request import Request
30
36
  from spiderweb.response import HttpResponse, TemplateResponse, JsonResponse
31
37
  from spiderweb.routes import RoutesMixin
32
38
  from spiderweb.secrets import FernetMixin
33
- from spiderweb.utils import get_http_status_by_code
39
+ from spiderweb.utils import get_http_status_by_code, convert_url_to_regex
34
40
 
35
- file_logger = logging.getLogger(__name__)
41
+ console_logger = logging.getLogger(__name__)
36
42
  logging.basicConfig(level=logging.INFO)
37
43
 
38
44
 
@@ -42,22 +48,34 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
42
48
  *,
43
49
  addr: str = None,
44
50
  port: int = None,
51
+ allowed_hosts: Sequence[str | re.Pattern] = None,
52
+ cors_allowed_origins: Sequence[str] = None,
53
+ cors_allowed_origin_regexes: Sequence[str] = None,
54
+ cors_allow_all_origins: bool = False,
55
+ cors_urls_regex: str | re.Pattern[str] = r"^.*$",
56
+ cors_allow_methods: Sequence[str] = None,
57
+ cors_allow_headers: Sequence[str] = None,
58
+ cors_expose_headers: Sequence[str] = None,
59
+ cors_preflight_max_age: int = 86400,
60
+ cors_allow_credentials: bool = False,
61
+ cors_allow_private_network: bool = False,
62
+ csrf_trusted_origins: Sequence[str] = None,
45
63
  db: Optional[Database] = None,
46
- templates_dirs: list[str] = None,
47
- middleware: list[str] = None,
64
+ templates_dirs: Sequence[str] = None,
65
+ middleware: Sequence[str] = None,
48
66
  append_slash: bool = False,
49
- staticfiles_dirs: list[str] = None,
50
- routes: list[tuple[str, Callable] | tuple[str, Callable, dict]] = None,
67
+ staticfiles_dirs: Sequence[str] = None,
68
+ routes: Sequence[tuple[str, Callable] | tuple[str, Callable, dict]] = None,
51
69
  error_routes: dict[int, Callable] = None,
52
70
  secret_key: str = None,
53
- session_max_age=60 * 60 * 24 * 14, # 2 weeks
54
- session_cookie_name="swsession",
55
- session_cookie_secure=False, # should be true if serving over HTTPS
56
- session_cookie_http_only=True,
57
- session_cookie_same_site="lax",
58
- session_cookie_path="/",
59
- log=None,
60
- **kwargs
71
+ session_max_age: int = 60 * 60 * 24 * 14, # 2 weeks
72
+ session_cookie_name: str = "swsession",
73
+ session_cookie_secure: bool = False, # should be true if serving over HTTPS
74
+ session_cookie_http_only: bool = True,
75
+ session_cookie_same_site: Literal["strict", "lax", "none"] = "lax",
76
+ session_cookie_path: str = "/",
77
+ log: Logger = None,
78
+ **kwargs,
61
79
  ):
62
80
  self._routes = {}
63
81
  self.routes = routes
@@ -69,8 +87,27 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
69
87
  self.append_slash = append_slash
70
88
  self.templates_dirs = templates_dirs
71
89
  self.staticfiles_dirs = staticfiles_dirs
72
- self.middleware = middleware if middleware else []
90
+ self._middleware: list[str] = middleware or []
91
+ self.middleware: list[Callable] = []
73
92
  self.secret_key = secret_key if secret_key else self.generate_key()
93
+ self._allowed_hosts = allowed_hosts or ["*"]
94
+ self.allowed_hosts = [convert_url_to_regex(i) for i in self._allowed_hosts]
95
+
96
+ self.cors_allowed_origins = cors_allowed_origins or []
97
+ self.cors_allowed_origin_regexes = cors_allowed_origin_regexes or []
98
+ self.cors_allow_all_origins = cors_allow_all_origins
99
+ self.cors_urls_regex = cors_urls_regex
100
+ self.cors_allow_methods = cors_allow_methods or DEFAULT_CORS_ALLOW_METHODS
101
+ self.cors_allow_headers = cors_allow_headers or DEFAULT_CORS_ALLOW_HEADERS
102
+ self.cors_expose_headers = cors_expose_headers or []
103
+ self.cors_preflight_max_age = cors_preflight_max_age
104
+ self.cors_allow_credentials = cors_allow_credentials
105
+ self.cors_allow_private_network = cors_allow_private_network
106
+
107
+ self._csrf_trusted_origins = csrf_trusted_origins or []
108
+ self.csrf_trusted_origins = [
109
+ convert_url_to_regex(i) for i in self._csrf_trusted_origins
110
+ ]
74
111
 
75
112
  self.extra_data = kwargs
76
113
 
@@ -84,7 +121,7 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
84
121
 
85
122
  self.DEFAULT_ENCODING = DEFAULT_ENCODING
86
123
  self.DEFAULT_ALLOWED_METHODS = DEFAULT_ALLOWED_METHODS
87
- self.log: logging.Logger = log if log else file_logger
124
+ self.log: logging.Logger = log if log else console_logger
88
125
 
89
126
  # for using .start() and .stop()
90
127
  self._thread: Optional[Thread] = None
@@ -108,7 +145,9 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
108
145
  self.add_error_routes()
109
146
 
110
147
  if self.templates_dirs:
111
- self.template_loader = Environment(loader=FileSystemLoader(self.templates_dirs))
148
+ self.template_loader = Environment(
149
+ loader=FileSystemLoader(self.templates_dirs)
150
+ )
112
151
  else:
113
152
  self.template_loader = None
114
153
  self.string_loader = Environment(loader=BaseLoader())
@@ -117,22 +156,34 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
117
156
  for static_dir in self.staticfiles_dirs:
118
157
  static_dir = pathlib.Path(static_dir)
119
158
  if not pathlib.Path(self.BASE_DIR / static_dir).exists():
120
- log.error(
159
+ self.log.error(
121
160
  f"Static files directory '{str(static_dir)}' does not exist."
122
161
  )
123
162
  raise ConfigError
124
163
  self.add_route(r"/static/<str:filename>", send_file) # noqa: F405
125
164
 
165
+ # finally, run the startup checks to verify everything is correct and happy.
166
+ self.log.info("Run startup checks...")
167
+ self.run_middleware_checks()
168
+
126
169
  def fire_response(self, start_response, request: Request, resp: HttpResponse):
127
170
  try:
128
171
  status = get_http_status_by_code(resp.status_code)
129
172
  cookies = []
130
- if "Set-Cookie" in resp.headers:
131
- cookies = resp.headers["Set-Cookie"]
132
- del resp.headers["Set-Cookie"]
173
+ varies = []
174
+ resp.headers = {k.replace("_", "-"): v for k, v in resp.headers.items()}
175
+ if "set-cookie" in resp.headers:
176
+ cookies = resp.headers["set-cookie"]
177
+ del resp.headers["set-cookie"]
178
+ if "vary" in resp.headers:
179
+ varies = resp.headers["vary"]
180
+ del resp.headers["vary"]
181
+ resp.headers = {k: str(v) for k, v in resp.headers.items()}
133
182
  headers = list(resp.headers.items())
134
183
  for c in cookies:
135
- headers.append(("Set-Cookie", c))
184
+ headers.append(("set-cookie", str(c)))
185
+ for v in varies:
186
+ headers.append(("vary", str(v)))
136
187
 
137
188
  start_response(status, headers)
138
189
 
@@ -173,7 +224,7 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
173
224
  ):
174
225
  try:
175
226
  status = get_http_status_by_code(500)
176
- headers = [("Content-type", "text/plain; charset=utf-8")]
227
+ headers = [("Content-Type", "text/plain; charset=utf-8")]
177
228
 
178
229
  start_response(status, headers)
179
230
 
@@ -190,7 +241,9 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
190
241
  def prepare_and_fire_response(self, start_response, request, resp) -> list[bytes]:
191
242
  try:
192
243
  if isinstance(resp, dict):
193
- return self.fire_response(start_response, request, JsonResponse(data=resp))
244
+ return self.fire_response(
245
+ start_response, request, JsonResponse(data=resp)
246
+ )
194
247
  if isinstance(resp, TemplateResponse):
195
248
  resp.set_template_loader(self.template_loader)
196
249
  resp.set_string_loader(self.string_loader)
@@ -208,10 +261,18 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
208
261
  start_response, request, self.get_error_route(500)(request)
209
262
  )
210
263
 
264
+ def check_valid_host(self, request) -> bool:
265
+ host = request.headers.get("http_host")
266
+ if not host:
267
+ return False
268
+ for option in self.allowed_hosts:
269
+ if re.match(option, host):
270
+ return True
271
+ return False
272
+
211
273
  def __call__(self, environ, start_response, *args, **kwargs):
212
274
  """Entry point for WSGI apps."""
213
275
  request = self.get_request(environ)
214
-
215
276
  try:
216
277
  handler, additional_args, allowed_methods = self.get_route(request.path)
217
278
  except NotFound:
@@ -224,6 +285,9 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
224
285
  # replace the potentially valid handler with the error route
225
286
  handler = self.get_error_route(405)
226
287
 
288
+ if not self.check_valid_host(request):
289
+ handler = self.get_error_route(403)
290
+
227
291
  if request.is_form_request():
228
292
  form_data = urlparse.parse_qs(request.content)
229
293
  for key, value in form_data.items():
@@ -1,9 +1,11 @@
1
1
  from typing import Callable, ClassVar
2
+ import sys
2
3
 
3
4
  from .base import SpiderwebMiddleware as SpiderwebMiddleware
5
+ from .cors import CorsMiddleware as CorsMiddleware
4
6
  from .csrf import CSRFMiddleware as CSRFMiddleware
5
7
  from .sessions import SessionMiddleware as SessionMiddleware
6
- from ..exceptions import ConfigError, UnusedMiddleware
8
+ from ..exceptions import ConfigError, UnusedMiddleware, StartupErrors
7
9
  from ..request import Request
8
10
  from ..response import HttpResponse
9
11
  from ..utils import import_by_string
@@ -12,19 +14,35 @@ from ..utils import import_by_string
12
14
  class MiddlewareMixin:
13
15
  """Cannot be called on its own. Requires context of SpiderwebRouter."""
14
16
 
17
+ _middleware: list[str]
15
18
  middleware: list[ClassVar]
16
19
  fire_response: Callable
17
20
 
18
21
  def init_middleware(self):
19
- if self.middleware:
22
+ if self._middleware:
20
23
  middleware_by_reference = []
21
- for m in self.middleware:
24
+ for m in self._middleware:
22
25
  try:
23
26
  middleware_by_reference.append(import_by_string(m)(server=self))
24
27
  except ImportError:
25
28
  raise ConfigError(f"Middleware '{m}' not found.")
26
29
  self.middleware = middleware_by_reference
27
30
 
31
+ def run_middleware_checks(self):
32
+ errors = []
33
+ for middleware in self.middleware:
34
+ if hasattr(middleware, "checks"):
35
+ for check in middleware.checks:
36
+ if issue := check(server=self).check():
37
+ errors.append(issue)
38
+
39
+ if errors:
40
+ # just show the messages
41
+ sys.tracebacklimit = 1
42
+ raise StartupErrors(
43
+ "Problems were identified during startup — cannot continue.", errors
44
+ )
45
+
28
46
  def process_request_middleware(self, request: Request) -> None | bool:
29
47
  for middleware in self.middleware:
30
48
  try:
@@ -30,4 +30,4 @@ class SpiderwebMiddleware:
30
30
  pass
31
31
 
32
32
  def on_error(self, request: Request, e: Exception) -> HttpResponse | None:
33
- pass
33
+ pass