pboot 3.2.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.
- pboot/__init__.py +39 -0
- pboot/__main__.py +3 -0
- pboot/app.py +1686 -0
- pboot/blueprints.py +128 -0
- pboot/cli.py +1126 -0
- pboot/config.py +367 -0
- pboot/ctx.py +540 -0
- pboot/debughelpers.py +179 -0
- pboot/globals.py +77 -0
- pboot/helpers.py +679 -0
- pboot/json/__init__.py +170 -0
- pboot/json/provider.py +215 -0
- pboot/json/tag.py +327 -0
- pboot/logging.py +79 -0
- pboot/py.typed +0 -0
- pboot/sansio/README.md +6 -0
- pboot/sansio/app.py +1014 -0
- pboot/sansio/blueprints.py +692 -0
- pboot/sansio/scaffold.py +800 -0
- pboot/sessions.py +385 -0
- pboot/signals.py +17 -0
- pboot/templating.py +212 -0
- pboot/testing.py +298 -0
- pboot/typing.py +87 -0
- pboot/views.py +191 -0
- pboot/wrappers.py +255 -0
- pboot-3.2.0.dist-info/METADATA +194 -0
- pboot-3.2.0.dist-info/RECORD +31 -0
- pboot-3.2.0.dist-info/WHEEL +4 -0
- pboot-3.2.0.dist-info/entry_points.txt +3 -0
- pboot-3.2.0.dist-info/licenses/LICENSE.txt +28 -0
pboot/debughelpers.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import typing as t
|
|
4
|
+
|
|
5
|
+
from jinja2.loaders import BaseLoader
|
|
6
|
+
from werkzeug.routing import RequestRedirect
|
|
7
|
+
|
|
8
|
+
from .blueprints import Blueprint
|
|
9
|
+
from .globals import _cv_app
|
|
10
|
+
from .sansio.app import App
|
|
11
|
+
|
|
12
|
+
if t.TYPE_CHECKING:
|
|
13
|
+
from .sansio.scaffold import Scaffold
|
|
14
|
+
from .wrappers import Request
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UnexpectedUnicodeError(AssertionError, UnicodeError):
|
|
18
|
+
"""Raised in places where we want some better error reporting for
|
|
19
|
+
unexpected unicode or binary data.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DebugFilesKeyError(KeyError, AssertionError):
|
|
24
|
+
"""Raised from request.files during debugging. The idea is that it can
|
|
25
|
+
provide a better error message than just a generic KeyError/BadRequest.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, request: Request, key: str) -> None:
|
|
29
|
+
form_matches = request.form.getlist(key)
|
|
30
|
+
buf = [
|
|
31
|
+
f"You tried to access the file {key!r} in the request.files"
|
|
32
|
+
" dictionary but it does not exist. The mimetype for the"
|
|
33
|
+
f" request is {request.mimetype!r} instead of"
|
|
34
|
+
" 'multipart/form-data' which means that no file contents"
|
|
35
|
+
" were transmitted. To fix this error you should provide"
|
|
36
|
+
' enctype="multipart/form-data" in your form.'
|
|
37
|
+
]
|
|
38
|
+
if form_matches:
|
|
39
|
+
names = ", ".join(repr(x) for x in form_matches)
|
|
40
|
+
buf.append(
|
|
41
|
+
"\n\nThe browser instead transmitted some file names. "
|
|
42
|
+
f"This was submitted: {names}"
|
|
43
|
+
)
|
|
44
|
+
self.msg = "".join(buf)
|
|
45
|
+
|
|
46
|
+
def __str__(self) -> str:
|
|
47
|
+
return self.msg
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class FormDataRoutingRedirect(AssertionError):
|
|
51
|
+
"""This exception is raised in debug mode if a routing redirect
|
|
52
|
+
would cause the browser to drop the method or body. This happens
|
|
53
|
+
when method is not GET, HEAD or OPTIONS and the status code is not
|
|
54
|
+
307 or 308.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, request: Request) -> None:
|
|
58
|
+
exc = request.routing_exception
|
|
59
|
+
assert isinstance(exc, RequestRedirect)
|
|
60
|
+
buf = [
|
|
61
|
+
f"A request was sent to '{request.url}', but routing issued"
|
|
62
|
+
f" a redirect to the canonical URL '{exc.new_url}'."
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
if f"{request.base_url}/" == exc.new_url.partition("?")[0]:
|
|
66
|
+
buf.append(
|
|
67
|
+
" The URL was defined with a trailing slash. Pboot"
|
|
68
|
+
" will redirect to the URL with a trailing slash if it"
|
|
69
|
+
" was accessed without one."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
buf.append(
|
|
73
|
+
" Send requests to the canonical URL, or use 307 or 308 for"
|
|
74
|
+
" routing redirects. Otherwise, browsers will drop form"
|
|
75
|
+
" data.\n\n"
|
|
76
|
+
"This exception is only raised in debug mode."
|
|
77
|
+
)
|
|
78
|
+
super().__init__("".join(buf))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def attach_enctype_error_multidict(request: Request) -> None:
|
|
82
|
+
"""Patch ``request.files.__getitem__`` to raise a descriptive error
|
|
83
|
+
about ``enctype=multipart/form-data``.
|
|
84
|
+
|
|
85
|
+
:param request: The request to patch.
|
|
86
|
+
:meta private:
|
|
87
|
+
"""
|
|
88
|
+
oldcls = request.files.__class__
|
|
89
|
+
|
|
90
|
+
class newcls(oldcls): # type: ignore[valid-type, misc]
|
|
91
|
+
def __getitem__(self, key: str) -> t.Any:
|
|
92
|
+
try:
|
|
93
|
+
return super().__getitem__(key)
|
|
94
|
+
except KeyError as e:
|
|
95
|
+
if key not in request.form:
|
|
96
|
+
raise
|
|
97
|
+
|
|
98
|
+
raise DebugFilesKeyError(request, key).with_traceback(
|
|
99
|
+
e.__traceback__
|
|
100
|
+
) from None
|
|
101
|
+
|
|
102
|
+
newcls.__name__ = oldcls.__name__
|
|
103
|
+
newcls.__module__ = oldcls.__module__
|
|
104
|
+
request.files.__class__ = newcls
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]:
|
|
108
|
+
yield f"class: {type(loader).__module__}.{type(loader).__name__}"
|
|
109
|
+
for key, value in sorted(loader.__dict__.items()):
|
|
110
|
+
if key.startswith("_"):
|
|
111
|
+
continue
|
|
112
|
+
if isinstance(value, (tuple, list)):
|
|
113
|
+
if not all(isinstance(x, str) for x in value):
|
|
114
|
+
continue
|
|
115
|
+
yield f"{key}:"
|
|
116
|
+
for item in value:
|
|
117
|
+
yield f" - {item}"
|
|
118
|
+
continue
|
|
119
|
+
elif not isinstance(value, (str, int, float, bool)):
|
|
120
|
+
continue
|
|
121
|
+
yield f"{key}: {value!r}"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def explain_template_loading_attempts(
|
|
125
|
+
app: App,
|
|
126
|
+
template: str,
|
|
127
|
+
attempts: list[
|
|
128
|
+
tuple[
|
|
129
|
+
BaseLoader,
|
|
130
|
+
Scaffold,
|
|
131
|
+
tuple[str, str | None, t.Callable[[], bool] | None] | None,
|
|
132
|
+
]
|
|
133
|
+
],
|
|
134
|
+
) -> None:
|
|
135
|
+
"""This should help developers understand what failed"""
|
|
136
|
+
info = [f"Locating template {template!r}:"]
|
|
137
|
+
total_found = 0
|
|
138
|
+
blueprint = None
|
|
139
|
+
|
|
140
|
+
if (ctx := _cv_app.get(None)) is not None and ctx.has_request:
|
|
141
|
+
blueprint = ctx.request.blueprint
|
|
142
|
+
|
|
143
|
+
for idx, (loader, srcobj, triple) in enumerate(attempts):
|
|
144
|
+
if isinstance(srcobj, App):
|
|
145
|
+
src_info = f"application {srcobj.import_name!r}"
|
|
146
|
+
elif isinstance(srcobj, Blueprint):
|
|
147
|
+
src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"
|
|
148
|
+
else:
|
|
149
|
+
src_info = repr(srcobj)
|
|
150
|
+
|
|
151
|
+
info.append(f"{idx + 1:5}: trying loader of {src_info}")
|
|
152
|
+
|
|
153
|
+
for line in _dump_loader_info(loader):
|
|
154
|
+
info.append(f" {line}")
|
|
155
|
+
|
|
156
|
+
if triple is None:
|
|
157
|
+
detail = "no match"
|
|
158
|
+
else:
|
|
159
|
+
detail = f"found ({triple[1] or '<string>'!r})"
|
|
160
|
+
total_found += 1
|
|
161
|
+
info.append(f" -> {detail}")
|
|
162
|
+
|
|
163
|
+
seems_fishy = False
|
|
164
|
+
if total_found == 0:
|
|
165
|
+
info.append("Error: the template could not be found.")
|
|
166
|
+
seems_fishy = True
|
|
167
|
+
elif total_found > 1:
|
|
168
|
+
info.append("Warning: multiple loaders returned a match for the template.")
|
|
169
|
+
seems_fishy = True
|
|
170
|
+
|
|
171
|
+
if blueprint is not None and seems_fishy:
|
|
172
|
+
info.append(
|
|
173
|
+
" The template was looked up from an endpoint that belongs"
|
|
174
|
+
f" to the blueprint {blueprint!r}."
|
|
175
|
+
)
|
|
176
|
+
info.append(" Maybe you did not place a template in the right folder?")
|
|
177
|
+
info.append(" See https://gitee.com/pboot-org/pboot/blob/main/docs/blueprints.rst")
|
|
178
|
+
|
|
179
|
+
app.logger.info("\n".join(info))
|
pboot/globals.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import typing as t
|
|
4
|
+
from contextvars import ContextVar
|
|
5
|
+
|
|
6
|
+
from werkzeug.local import LocalProxy
|
|
7
|
+
|
|
8
|
+
if t.TYPE_CHECKING: # pragma: no cover
|
|
9
|
+
from .app import Pboot
|
|
10
|
+
from .ctx import _AppCtxGlobals
|
|
11
|
+
from .ctx import AppContext
|
|
12
|
+
from .sessions import SessionMixin
|
|
13
|
+
from .wrappers import Request
|
|
14
|
+
|
|
15
|
+
T = t.TypeVar("T", covariant=True)
|
|
16
|
+
|
|
17
|
+
class ProxyMixin(t.Protocol[T]):
|
|
18
|
+
def _get_current_object(self) -> T: ...
|
|
19
|
+
|
|
20
|
+
# These subclasses inform type checkers that the proxy objects look like the
|
|
21
|
+
# proxied type along with the _get_current_object method.
|
|
22
|
+
class PbootProxy(ProxyMixin[Pboot], Pboot): ...
|
|
23
|
+
|
|
24
|
+
class AppContextProxy(ProxyMixin[AppContext], AppContext): ...
|
|
25
|
+
|
|
26
|
+
class _AppCtxGlobalsProxy(ProxyMixin[_AppCtxGlobals], _AppCtxGlobals): ...
|
|
27
|
+
|
|
28
|
+
class RequestProxy(ProxyMixin[Request], Request): ...
|
|
29
|
+
|
|
30
|
+
class SessionMixinProxy(ProxyMixin[SessionMixin], SessionMixin): ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_no_app_msg = """\
|
|
34
|
+
Working outside of application context.
|
|
35
|
+
|
|
36
|
+
Attempted to use functionality that expected a current application to be set. To
|
|
37
|
+
solve this, set up an app context using 'with app.app_context()'. See the
|
|
38
|
+
documentation on app context for more information.\
|
|
39
|
+
"""
|
|
40
|
+
_cv_app: ContextVar[AppContext] = ContextVar("pboot.app_ctx")
|
|
41
|
+
app_ctx: AppContextProxy = LocalProxy( # type: ignore[assignment]
|
|
42
|
+
_cv_app, unbound_message=_no_app_msg
|
|
43
|
+
)
|
|
44
|
+
current_app: PbootProxy = LocalProxy( # type: ignore[assignment]
|
|
45
|
+
_cv_app, "app", unbound_message=_no_app_msg
|
|
46
|
+
)
|
|
47
|
+
g: _AppCtxGlobalsProxy = LocalProxy( # type: ignore[assignment]
|
|
48
|
+
_cv_app, "g", unbound_message=_no_app_msg
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
_no_req_msg = """\
|
|
52
|
+
Working outside of request context.
|
|
53
|
+
|
|
54
|
+
Attempted to use functionality that expected an active HTTP request. See the
|
|
55
|
+
documentation on request context for more information.\
|
|
56
|
+
"""
|
|
57
|
+
request: RequestProxy = LocalProxy( # type: ignore[assignment]
|
|
58
|
+
_cv_app, "request", unbound_message=_no_req_msg
|
|
59
|
+
)
|
|
60
|
+
session: SessionMixinProxy = LocalProxy( # type: ignore[assignment]
|
|
61
|
+
_cv_app, "session", unbound_message=_no_req_msg
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def __getattr__(name: str) -> t.Any:
|
|
66
|
+
import warnings
|
|
67
|
+
|
|
68
|
+
if name == "request_ctx":
|
|
69
|
+
warnings.warn(
|
|
70
|
+
"'request_ctx' has merged with 'app_ctx', and will be removed"
|
|
71
|
+
" in Pboot 4.0. Use 'app_ctx' instead.",
|
|
72
|
+
DeprecationWarning,
|
|
73
|
+
stacklevel=2,
|
|
74
|
+
)
|
|
75
|
+
return app_ctx
|
|
76
|
+
|
|
77
|
+
raise AttributeError(name)
|