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/helpers.py
ADDED
|
@@ -0,0 +1,679 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import typing as t
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from functools import cache
|
|
9
|
+
from functools import update_wrapper
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
|
|
12
|
+
import werkzeug.utils
|
|
13
|
+
from werkzeug.exceptions import abort as _wz_abort
|
|
14
|
+
from werkzeug.utils import redirect as _wz_redirect
|
|
15
|
+
from werkzeug.wrappers import Response as BaseResponse
|
|
16
|
+
|
|
17
|
+
from .globals import _cv_app
|
|
18
|
+
from .globals import app_ctx
|
|
19
|
+
from .globals import current_app
|
|
20
|
+
from .globals import request
|
|
21
|
+
from .globals import session
|
|
22
|
+
from .signals import message_flashed
|
|
23
|
+
|
|
24
|
+
if t.TYPE_CHECKING: # pragma: no cover
|
|
25
|
+
from .wrappers import Response
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def get_debug_flag() -> bool:
|
|
29
|
+
"""Get whether debug mode should be enabled for the app, indicated by the
|
|
30
|
+
:envvar:`PBOOT_DEBUG` environment variable. The default is ``False``.
|
|
31
|
+
"""
|
|
32
|
+
val = os.environ.get("PBOOT_DEBUG")
|
|
33
|
+
return bool(val and val.lower() not in {"0", "false", "no"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def get_load_dotenv(default: bool = True) -> bool:
|
|
37
|
+
"""Get whether the user has disabled loading default dotenv files by
|
|
38
|
+
setting :envvar:`PBOOT_SKIP_DOTENV`. The default is ``True``, load
|
|
39
|
+
the files.
|
|
40
|
+
|
|
41
|
+
:param default: What to return if the env var isn't set.
|
|
42
|
+
"""
|
|
43
|
+
val = os.environ.get("PBOOT_SKIP_DOTENV")
|
|
44
|
+
|
|
45
|
+
if not val:
|
|
46
|
+
return default
|
|
47
|
+
|
|
48
|
+
return val.lower() in ("0", "false", "no")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@t.overload
|
|
52
|
+
def stream_with_context(
|
|
53
|
+
generator_or_function: t.Iterator[t.AnyStr],
|
|
54
|
+
) -> t.Iterator[t.AnyStr]: ...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@t.overload
|
|
58
|
+
def stream_with_context(
|
|
59
|
+
generator_or_function: t.Callable[..., t.Iterator[t.AnyStr]],
|
|
60
|
+
) -> t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]: ...
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def stream_with_context(
|
|
64
|
+
generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],
|
|
65
|
+
) -> t.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]:
|
|
66
|
+
"""Wrap a response generator function so that it runs inside the current
|
|
67
|
+
request context. This keeps :data:`.request`, :data:`.session`, and :data:`.g`
|
|
68
|
+
available, even though at the point the generator runs the request context
|
|
69
|
+
will typically have ended.
|
|
70
|
+
|
|
71
|
+
.. warning::
|
|
72
|
+
|
|
73
|
+
Due to the following caveat, it is often safer to pass the data you
|
|
74
|
+
need as arguments to the generator, rather than relying on the context
|
|
75
|
+
objects.
|
|
76
|
+
|
|
77
|
+
More headers cannot be sent after the body has begun. Therefore, you must
|
|
78
|
+
make sure all headers are set before starting the response. In particular,
|
|
79
|
+
if the generator will access ``session``, be sure to do so in the view as
|
|
80
|
+
well so that the ``Vary: cookie`` header will be set. Do not modify the
|
|
81
|
+
session in the generator, as the ``Set-Cookie`` header will already be sent.
|
|
82
|
+
|
|
83
|
+
Use it as a decorator on a generator function:
|
|
84
|
+
|
|
85
|
+
.. code-block:: python
|
|
86
|
+
|
|
87
|
+
from pboot import stream_with_context, request, Response
|
|
88
|
+
|
|
89
|
+
@app.get("/stream")
|
|
90
|
+
def streamed_response():
|
|
91
|
+
@stream_with_context
|
|
92
|
+
def generate():
|
|
93
|
+
yield "Hello "
|
|
94
|
+
yield request.args["name"]
|
|
95
|
+
yield "!"
|
|
96
|
+
|
|
97
|
+
return Response(generate())
|
|
98
|
+
|
|
99
|
+
Or use it as a wrapper around a created generator:
|
|
100
|
+
|
|
101
|
+
.. code-block:: python
|
|
102
|
+
|
|
103
|
+
from pboot import stream_with_context, request, Response
|
|
104
|
+
|
|
105
|
+
@app.get("/stream")
|
|
106
|
+
def streamed_response():
|
|
107
|
+
def generate():
|
|
108
|
+
yield "Hello "
|
|
109
|
+
yield request.args["name"]
|
|
110
|
+
yield "!"
|
|
111
|
+
|
|
112
|
+
return Response(stream_with_context(generate()))
|
|
113
|
+
|
|
114
|
+
.. versionadded:: 0.9
|
|
115
|
+
"""
|
|
116
|
+
try:
|
|
117
|
+
gen = iter(generator_or_function) # type: ignore[arg-type]
|
|
118
|
+
except TypeError:
|
|
119
|
+
|
|
120
|
+
def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:
|
|
121
|
+
gen = generator_or_function(*args, **kwargs) # type: ignore[operator]
|
|
122
|
+
return stream_with_context(gen)
|
|
123
|
+
|
|
124
|
+
return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]
|
|
125
|
+
|
|
126
|
+
def generator() -> t.Iterator[t.AnyStr]:
|
|
127
|
+
if (ctx := _cv_app.get(None)) is None:
|
|
128
|
+
raise RuntimeError(
|
|
129
|
+
"'stream_with_context' can only be used when a request"
|
|
130
|
+
" context is active, such as in a view function."
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
with ctx:
|
|
134
|
+
yield None # type: ignore[misc]
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
yield from gen
|
|
138
|
+
finally:
|
|
139
|
+
# Clean up in case the user wrapped a WSGI iterator.
|
|
140
|
+
if hasattr(gen, "close"):
|
|
141
|
+
gen.close()
|
|
142
|
+
|
|
143
|
+
# Execute the generator to the sentinel value. This captures the current
|
|
144
|
+
# context and pushes it to preserve it. Further iteration will yield from
|
|
145
|
+
# the original iterator.
|
|
146
|
+
wrapped_g = generator()
|
|
147
|
+
next(wrapped_g)
|
|
148
|
+
return wrapped_g
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def make_response(*args: t.Any) -> Response:
|
|
152
|
+
"""Sometimes it is necessary to set additional headers in a view. Because
|
|
153
|
+
views do not have to return response objects but can return a value that
|
|
154
|
+
is converted into a response object by Pboot itself, it becomes tricky to
|
|
155
|
+
add headers to it. This function can be called instead of using a return
|
|
156
|
+
and you will get a response object which you can use to attach headers.
|
|
157
|
+
|
|
158
|
+
If view looked like this and you want to add a new header::
|
|
159
|
+
|
|
160
|
+
def index():
|
|
161
|
+
return render_template('index.html', foo=42)
|
|
162
|
+
|
|
163
|
+
You can now do something like this::
|
|
164
|
+
|
|
165
|
+
def index():
|
|
166
|
+
response = make_response(render_template('index.html', foo=42))
|
|
167
|
+
response.headers['X-Parachutes'] = 'parachutes are cool'
|
|
168
|
+
return response
|
|
169
|
+
|
|
170
|
+
This function accepts the very same arguments you can return from a
|
|
171
|
+
view function. This for example creates a response with a 404 error
|
|
172
|
+
code::
|
|
173
|
+
|
|
174
|
+
response = make_response(render_template('not_found.html'), 404)
|
|
175
|
+
|
|
176
|
+
The other use case of this function is to force the return value of a
|
|
177
|
+
view function into a response which is helpful with view
|
|
178
|
+
decorators::
|
|
179
|
+
|
|
180
|
+
response = make_response(view_function())
|
|
181
|
+
response.headers['X-Parachutes'] = 'parachutes are cool'
|
|
182
|
+
|
|
183
|
+
Internally this function does the following things:
|
|
184
|
+
|
|
185
|
+
- if no arguments are passed, it creates a new response argument
|
|
186
|
+
- if one argument is passed, :meth:`pboot.Pboot.make_response`
|
|
187
|
+
is invoked with it.
|
|
188
|
+
- if more than one argument is passed, the arguments are passed
|
|
189
|
+
to the :meth:`pboot.Pboot.make_response` function as tuple.
|
|
190
|
+
|
|
191
|
+
.. versionadded:: 0.6
|
|
192
|
+
"""
|
|
193
|
+
if not args:
|
|
194
|
+
return current_app.response_class()
|
|
195
|
+
if len(args) == 1:
|
|
196
|
+
args = args[0]
|
|
197
|
+
return current_app.make_response(args)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def url_for(
|
|
201
|
+
endpoint: str,
|
|
202
|
+
*,
|
|
203
|
+
_anchor: str | None = None,
|
|
204
|
+
_method: str | None = None,
|
|
205
|
+
_scheme: str | None = None,
|
|
206
|
+
_external: bool | None = None,
|
|
207
|
+
**values: t.Any,
|
|
208
|
+
) -> str:
|
|
209
|
+
"""Generate a URL to the given endpoint with the given values.
|
|
210
|
+
|
|
211
|
+
This requires an active request or application context, and calls
|
|
212
|
+
:meth:`current_app.url_for() <pboot.Pboot.url_for>`. See that method
|
|
213
|
+
for full documentation.
|
|
214
|
+
|
|
215
|
+
:param endpoint: The endpoint name associated with the URL to
|
|
216
|
+
generate. If this starts with a ``.``, the current blueprint
|
|
217
|
+
name (if any) will be used.
|
|
218
|
+
:param _anchor: If given, append this as ``#anchor`` to the URL.
|
|
219
|
+
:param _method: If given, generate the URL associated with this
|
|
220
|
+
method for the endpoint.
|
|
221
|
+
:param _scheme: If given, the URL will have this scheme if it is
|
|
222
|
+
external.
|
|
223
|
+
:param _external: If given, prefer the URL to be internal (False) or
|
|
224
|
+
require it to be external (True). External URLs include the
|
|
225
|
+
scheme and domain. When not in an active request, URLs are
|
|
226
|
+
external by default.
|
|
227
|
+
:param values: Values to use for the variable parts of the URL rule.
|
|
228
|
+
Unknown keys are appended as query string arguments, like
|
|
229
|
+
``?a=b&c=d``.
|
|
230
|
+
|
|
231
|
+
.. versionchanged:: 2.2
|
|
232
|
+
Calls ``current_app.url_for``, allowing an app to override the
|
|
233
|
+
behavior.
|
|
234
|
+
|
|
235
|
+
.. versionchanged:: 0.10
|
|
236
|
+
The ``_scheme`` parameter was added.
|
|
237
|
+
|
|
238
|
+
.. versionchanged:: 0.9
|
|
239
|
+
The ``_anchor`` and ``_method`` parameters were added.
|
|
240
|
+
|
|
241
|
+
.. versionchanged:: 0.9
|
|
242
|
+
Calls ``app.handle_url_build_error`` on build errors.
|
|
243
|
+
"""
|
|
244
|
+
return current_app.url_for(
|
|
245
|
+
endpoint,
|
|
246
|
+
_anchor=_anchor,
|
|
247
|
+
_method=_method,
|
|
248
|
+
_scheme=_scheme,
|
|
249
|
+
_external=_external,
|
|
250
|
+
**values,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def redirect(
|
|
255
|
+
location: str, code: int = 303, Response: type[BaseResponse] | None = None
|
|
256
|
+
) -> BaseResponse:
|
|
257
|
+
"""Create a redirect response object.
|
|
258
|
+
|
|
259
|
+
If :data:`~pboot.current_app` is available, it will use its
|
|
260
|
+
:meth:`~pboot.Pboot.redirect` method, otherwise it will use
|
|
261
|
+
:func:`werkzeug.utils.redirect`.
|
|
262
|
+
|
|
263
|
+
:param location: The URL to redirect to.
|
|
264
|
+
:param code: The status code for the redirect.
|
|
265
|
+
:param Response: The response class to use. Not used when
|
|
266
|
+
``current_app`` is active, which uses ``app.response_class``.
|
|
267
|
+
|
|
268
|
+
.. versionchanged:: 3.2
|
|
269
|
+
``code`` defaults to ``303`` instead of ``302``.
|
|
270
|
+
|
|
271
|
+
.. versionadded:: 2.2
|
|
272
|
+
Calls ``current_app.redirect`` if available instead of always
|
|
273
|
+
using Werkzeug's default ``redirect``.
|
|
274
|
+
"""
|
|
275
|
+
if (ctx := _cv_app.get(None)) is not None:
|
|
276
|
+
return ctx.app.redirect(location, code=code)
|
|
277
|
+
|
|
278
|
+
return _wz_redirect(location, code=code, Response=Response)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:
|
|
282
|
+
"""Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given
|
|
283
|
+
status code.
|
|
284
|
+
|
|
285
|
+
If :data:`~pboot.current_app` is available, it will call its
|
|
286
|
+
:attr:`~pboot.Pboot.aborter` object, otherwise it will use
|
|
287
|
+
:func:`werkzeug.exceptions.abort`.
|
|
288
|
+
|
|
289
|
+
:param code: The status code for the exception, which must be
|
|
290
|
+
registered in ``app.aborter``.
|
|
291
|
+
:param args: Passed to the exception.
|
|
292
|
+
:param kwargs: Passed to the exception.
|
|
293
|
+
|
|
294
|
+
.. versionadded:: 2.2
|
|
295
|
+
Calls ``current_app.aborter`` if available instead of always
|
|
296
|
+
using Werkzeug's default ``abort``.
|
|
297
|
+
"""
|
|
298
|
+
if (ctx := _cv_app.get(None)) is not None:
|
|
299
|
+
ctx.app.aborter(code, *args, **kwargs)
|
|
300
|
+
|
|
301
|
+
_wz_abort(code, *args, **kwargs)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def get_template_attribute(template_name: str, attribute: str) -> t.Any:
|
|
305
|
+
"""Loads a macro (or variable) a template exports. This can be used to
|
|
306
|
+
invoke a macro from within Python code. If you for example have a
|
|
307
|
+
template named :file:`_cider.html` with the following contents:
|
|
308
|
+
|
|
309
|
+
.. sourcecode:: html+jinja
|
|
310
|
+
|
|
311
|
+
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
|
|
312
|
+
|
|
313
|
+
You can access this from Python code like this::
|
|
314
|
+
|
|
315
|
+
hello = get_template_attribute('_cider.html', 'hello')
|
|
316
|
+
return hello('World')
|
|
317
|
+
|
|
318
|
+
.. versionadded:: 0.2
|
|
319
|
+
|
|
320
|
+
:param template_name: the name of the template
|
|
321
|
+
:param attribute: the name of the variable of macro to access
|
|
322
|
+
"""
|
|
323
|
+
return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def flash(message: str, category: str = "message") -> None:
|
|
327
|
+
"""Flashes a message to the next request. In order to remove the
|
|
328
|
+
flashed message from the session and to display it to the user,
|
|
329
|
+
the template has to call :func:`get_flashed_messages`.
|
|
330
|
+
|
|
331
|
+
.. versionchanged:: 0.3
|
|
332
|
+
`category` parameter added.
|
|
333
|
+
|
|
334
|
+
:param message: the message to be flashed.
|
|
335
|
+
:param category: the category for the message. The following values
|
|
336
|
+
are recommended: ``'message'`` for any kind of message,
|
|
337
|
+
``'error'`` for errors, ``'info'`` for information
|
|
338
|
+
messages and ``'warning'`` for warnings. However any
|
|
339
|
+
kind of string can be used as category.
|
|
340
|
+
"""
|
|
341
|
+
# Original implementation:
|
|
342
|
+
#
|
|
343
|
+
# session.setdefault('_flashes', []).append((category, message))
|
|
344
|
+
#
|
|
345
|
+
# This assumed that changes made to mutable structures in the session are
|
|
346
|
+
# always in sync with the session object, which is not true for session
|
|
347
|
+
# implementations that use external storage for keeping their keys/values.
|
|
348
|
+
flashes = session.get("_flashes", [])
|
|
349
|
+
flashes.append((category, message))
|
|
350
|
+
session["_flashes"] = flashes
|
|
351
|
+
app = current_app._get_current_object()
|
|
352
|
+
message_flashed.send(
|
|
353
|
+
app,
|
|
354
|
+
_async_wrapper=app.ensure_sync,
|
|
355
|
+
message=message,
|
|
356
|
+
category=category,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def get_flashed_messages(
|
|
361
|
+
with_categories: bool = False, category_filter: t.Iterable[str] = ()
|
|
362
|
+
) -> list[str] | list[tuple[str, str]]:
|
|
363
|
+
"""Pulls all flashed messages from the session and returns them.
|
|
364
|
+
Further calls in the same request to the function will return
|
|
365
|
+
the same messages. By default just the messages are returned,
|
|
366
|
+
but when `with_categories` is set to ``True``, the return value will
|
|
367
|
+
be a list of tuples in the form ``(category, message)`` instead.
|
|
368
|
+
|
|
369
|
+
Filter the flashed messages to one or more categories by providing those
|
|
370
|
+
categories in `category_filter`. This allows rendering categories in
|
|
371
|
+
separate html blocks. The `with_categories` and `category_filter`
|
|
372
|
+
arguments are distinct:
|
|
373
|
+
|
|
374
|
+
* `with_categories` controls whether categories are returned with message
|
|
375
|
+
text (``True`` gives a tuple, where ``False`` gives just the message text).
|
|
376
|
+
* `category_filter` filters the messages down to only those matching the
|
|
377
|
+
provided categories.
|
|
378
|
+
|
|
379
|
+
See :doc:`/patterns/flashing` for examples.
|
|
380
|
+
|
|
381
|
+
.. versionchanged:: 0.3
|
|
382
|
+
`with_categories` parameter added.
|
|
383
|
+
|
|
384
|
+
.. versionchanged:: 0.9
|
|
385
|
+
`category_filter` parameter added.
|
|
386
|
+
|
|
387
|
+
:param with_categories: set to ``True`` to also receive categories.
|
|
388
|
+
:param category_filter: filter of categories to limit return values. Only
|
|
389
|
+
categories in the list will be returned.
|
|
390
|
+
"""
|
|
391
|
+
flashes = app_ctx._flashes
|
|
392
|
+
if flashes is None:
|
|
393
|
+
flashes = session.pop("_flashes") if "_flashes" in session else []
|
|
394
|
+
app_ctx._flashes = flashes
|
|
395
|
+
if category_filter:
|
|
396
|
+
flashes = list(filter(lambda f: f[0] in category_filter, flashes))
|
|
397
|
+
if not with_categories:
|
|
398
|
+
return [x[1] for x in flashes]
|
|
399
|
+
return flashes
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:
|
|
403
|
+
ctx = app_ctx._get_current_object()
|
|
404
|
+
|
|
405
|
+
if kwargs.get("max_age") is None:
|
|
406
|
+
kwargs["max_age"] = ctx.app.get_send_file_max_age
|
|
407
|
+
|
|
408
|
+
kwargs.update(
|
|
409
|
+
environ=ctx.request.environ,
|
|
410
|
+
use_x_sendfile=ctx.app.config["USE_X_SENDFILE"],
|
|
411
|
+
response_class=ctx.app.response_class,
|
|
412
|
+
_root_path=ctx.app.root_path,
|
|
413
|
+
)
|
|
414
|
+
return kwargs
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def send_file(
|
|
418
|
+
path_or_file: os.PathLike[t.AnyStr] | str | t.IO[bytes],
|
|
419
|
+
mimetype: str | None = None,
|
|
420
|
+
as_attachment: bool = False,
|
|
421
|
+
download_name: str | None = None,
|
|
422
|
+
conditional: bool = True,
|
|
423
|
+
etag: bool | str = True,
|
|
424
|
+
last_modified: datetime | int | float | None = None,
|
|
425
|
+
max_age: None | (int | t.Callable[[str | None], int | None]) = None,
|
|
426
|
+
) -> Response:
|
|
427
|
+
"""Send the contents of a file to the client.
|
|
428
|
+
|
|
429
|
+
The first argument can be a file path or a file-like object. Paths
|
|
430
|
+
are preferred in most cases because Werkzeug can manage the file and
|
|
431
|
+
get extra information from the path. Passing a file-like object
|
|
432
|
+
requires that the file is opened in binary mode, and is mostly
|
|
433
|
+
useful when building a file in memory with :class:`io.BytesIO`.
|
|
434
|
+
|
|
435
|
+
Never pass file paths provided by a user. The path is assumed to be
|
|
436
|
+
trusted, so a user could craft a path to access a file you didn't
|
|
437
|
+
intend. Use :func:`send_from_directory` to safely serve
|
|
438
|
+
user-requested paths from within a directory.
|
|
439
|
+
|
|
440
|
+
If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
|
|
441
|
+
used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
|
|
442
|
+
if the HTTP server supports ``X-Sendfile``, configuring Pboot with
|
|
443
|
+
``USE_X_SENDFILE = True`` will tell the server to send the given
|
|
444
|
+
path, which is much more efficient than reading it in Python.
|
|
445
|
+
|
|
446
|
+
:param path_or_file: The path to the file to send, relative to the
|
|
447
|
+
current working directory if a relative path is given.
|
|
448
|
+
Alternatively, a file-like object opened in binary mode; make
|
|
449
|
+
sure to call ``seek(0)`` if it was already read.
|
|
450
|
+
:param mimetype: The MIME type to send for the file. If not
|
|
451
|
+
provided, it will try to detect it from the file name.
|
|
452
|
+
:param as_attachment: Indicate to a browser that it should offer to
|
|
453
|
+
save the file instead of displaying it.
|
|
454
|
+
:param download_name: The default name browsers will use when saving
|
|
455
|
+
the file. Defaults to the passed file name.
|
|
456
|
+
:param conditional: Enable conditional and range responses based on
|
|
457
|
+
request headers. Requires passing a file path and ``environ``.
|
|
458
|
+
:param etag: Calculate an ETag for the file, which requires passing
|
|
459
|
+
a file path. Can also be a string to use instead.
|
|
460
|
+
:param last_modified: The last modified time to send for the file,
|
|
461
|
+
in seconds. If not provided, it will try to detect it from the
|
|
462
|
+
file path.
|
|
463
|
+
:param max_age: How long the client should cache the file, in
|
|
464
|
+
seconds. If set, ``Cache-Control`` will be ``public``, otherwise
|
|
465
|
+
it will be ``no-cache`` to prefer conditional caching.
|
|
466
|
+
|
|
467
|
+
.. versionchanged:: 2.0
|
|
468
|
+
``download_name`` replaces the ``attachment_filename``
|
|
469
|
+
parameter. If ``as_attachment=False``, it is passed with
|
|
470
|
+
``Content-Disposition: inline`` instead.
|
|
471
|
+
|
|
472
|
+
.. versionchanged:: 2.0
|
|
473
|
+
``max_age`` replaces the ``cache_timeout`` parameter.
|
|
474
|
+
``conditional`` is enabled and ``max_age`` is not set by
|
|
475
|
+
default.
|
|
476
|
+
|
|
477
|
+
.. versionchanged:: 2.0
|
|
478
|
+
``etag`` replaces the ``add_etags`` parameter. It can be a
|
|
479
|
+
string to use instead of generating one.
|
|
480
|
+
|
|
481
|
+
.. versionchanged:: 2.0
|
|
482
|
+
Passing a file-like object that inherits from
|
|
483
|
+
:class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
|
|
484
|
+
than sending an empty file.
|
|
485
|
+
|
|
486
|
+
.. versionadded:: 2.0
|
|
487
|
+
Moved the implementation to Werkzeug. This is now a wrapper to
|
|
488
|
+
pass some Pboot-specific arguments.
|
|
489
|
+
|
|
490
|
+
.. versionchanged:: 1.1
|
|
491
|
+
``filename`` may be a :class:`~os.PathLike` object.
|
|
492
|
+
|
|
493
|
+
.. versionchanged:: 1.1
|
|
494
|
+
Passing a :class:`~io.BytesIO` object supports range requests.
|
|
495
|
+
|
|
496
|
+
.. versionchanged:: 1.0.3
|
|
497
|
+
Filenames are encoded with ASCII instead of Latin-1 for broader
|
|
498
|
+
compatibility with WSGI servers.
|
|
499
|
+
|
|
500
|
+
.. versionchanged:: 1.0
|
|
501
|
+
UTF-8 filenames as specified in :rfc:`2231` are supported.
|
|
502
|
+
|
|
503
|
+
.. versionchanged:: 0.12
|
|
504
|
+
The filename is no longer automatically inferred from file
|
|
505
|
+
objects. If you want to use automatic MIME and etag support,
|
|
506
|
+
pass a filename via ``filename_or_fp`` or
|
|
507
|
+
``attachment_filename``.
|
|
508
|
+
|
|
509
|
+
.. versionchanged:: 0.12
|
|
510
|
+
``attachment_filename`` is preferred over ``filename`` for MIME
|
|
511
|
+
detection.
|
|
512
|
+
|
|
513
|
+
.. versionchanged:: 0.9
|
|
514
|
+
``cache_timeout`` defaults to
|
|
515
|
+
:meth:`Pboot.get_send_file_max_age`.
|
|
516
|
+
|
|
517
|
+
.. versionchanged:: 0.7
|
|
518
|
+
MIME guessing and etag support for file-like objects was
|
|
519
|
+
removed because it was unreliable. Pass a filename if you are
|
|
520
|
+
able to, otherwise attach an etag yourself.
|
|
521
|
+
|
|
522
|
+
.. versionchanged:: 0.5
|
|
523
|
+
The ``add_etags``, ``cache_timeout`` and ``conditional``
|
|
524
|
+
parameters were added. The default behavior is to add etags.
|
|
525
|
+
|
|
526
|
+
.. versionadded:: 0.2
|
|
527
|
+
"""
|
|
528
|
+
return werkzeug.utils.send_file( # type: ignore[return-value]
|
|
529
|
+
**_prepare_send_file_kwargs(
|
|
530
|
+
path_or_file=path_or_file,
|
|
531
|
+
environ=request.environ,
|
|
532
|
+
mimetype=mimetype,
|
|
533
|
+
as_attachment=as_attachment,
|
|
534
|
+
download_name=download_name,
|
|
535
|
+
conditional=conditional,
|
|
536
|
+
etag=etag,
|
|
537
|
+
last_modified=last_modified,
|
|
538
|
+
max_age=max_age,
|
|
539
|
+
)
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def send_from_directory(
|
|
544
|
+
directory: os.PathLike[str] | str,
|
|
545
|
+
path: os.PathLike[str] | str,
|
|
546
|
+
**kwargs: t.Any,
|
|
547
|
+
) -> Response:
|
|
548
|
+
"""Send a file from within a directory using :func:`send_file`.
|
|
549
|
+
|
|
550
|
+
.. code-block:: python
|
|
551
|
+
|
|
552
|
+
@app.route("/uploads/<path:name>")
|
|
553
|
+
def download_file(name):
|
|
554
|
+
return send_from_directory(
|
|
555
|
+
app.config['UPLOAD_FOLDER'], name, as_attachment=True
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
This is a secure way to serve files from a folder, such as static
|
|
559
|
+
files or uploads. Uses :func:`~werkzeug.security.safe_join` to
|
|
560
|
+
ensure the path coming from the client is not maliciously crafted to
|
|
561
|
+
point outside the specified directory.
|
|
562
|
+
|
|
563
|
+
If the final path does not point to an existing regular file,
|
|
564
|
+
raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
|
|
565
|
+
|
|
566
|
+
:param directory: The directory that ``path`` must be located under,
|
|
567
|
+
relative to the current application's root path. This *must not*
|
|
568
|
+
be a value provided by the client, otherwise it becomes insecure.
|
|
569
|
+
:param path: The path to the file to send, relative to
|
|
570
|
+
``directory``.
|
|
571
|
+
:param kwargs: Arguments to pass to :func:`send_file`.
|
|
572
|
+
|
|
573
|
+
.. versionchanged:: 2.0
|
|
574
|
+
``path`` replaces the ``filename`` parameter.
|
|
575
|
+
|
|
576
|
+
.. versionadded:: 2.0
|
|
577
|
+
Moved the implementation to Werkzeug. This is now a wrapper to
|
|
578
|
+
pass some Pboot-specific arguments.
|
|
579
|
+
|
|
580
|
+
.. versionadded:: 0.5
|
|
581
|
+
"""
|
|
582
|
+
return werkzeug.utils.send_from_directory( # type: ignore[return-value]
|
|
583
|
+
directory, path, **_prepare_send_file_kwargs(**kwargs)
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def get_root_path(import_name: str) -> str:
|
|
588
|
+
"""Find the root path of a package, or the path that contains a
|
|
589
|
+
module. If it cannot be found, returns the current working
|
|
590
|
+
directory.
|
|
591
|
+
|
|
592
|
+
Not to be confused with the value returned by :func:`find_package`.
|
|
593
|
+
|
|
594
|
+
:meta private:
|
|
595
|
+
"""
|
|
596
|
+
# Module already imported and has a file attribute. Use that first.
|
|
597
|
+
mod = sys.modules.get(import_name)
|
|
598
|
+
|
|
599
|
+
if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None:
|
|
600
|
+
return os.path.dirname(os.path.abspath(mod.__file__))
|
|
601
|
+
|
|
602
|
+
# Next attempt: check the loader.
|
|
603
|
+
try:
|
|
604
|
+
spec = importlib.util.find_spec(import_name)
|
|
605
|
+
|
|
606
|
+
if spec is None:
|
|
607
|
+
raise ValueError
|
|
608
|
+
except (ImportError, ValueError):
|
|
609
|
+
loader = None
|
|
610
|
+
else:
|
|
611
|
+
loader = spec.loader
|
|
612
|
+
|
|
613
|
+
# Loader does not exist or we're referring to an unloaded main
|
|
614
|
+
# module or a main module without path (interactive sessions), go
|
|
615
|
+
# with the current working directory.
|
|
616
|
+
if loader is None:
|
|
617
|
+
return os.getcwd()
|
|
618
|
+
|
|
619
|
+
if hasattr(loader, "get_filename"):
|
|
620
|
+
filepath = loader.get_filename(import_name) # pyright: ignore
|
|
621
|
+
else:
|
|
622
|
+
# Fall back to imports.
|
|
623
|
+
__import__(import_name)
|
|
624
|
+
mod = sys.modules[import_name]
|
|
625
|
+
filepath = getattr(mod, "__file__", None)
|
|
626
|
+
|
|
627
|
+
# If we don't have a file path it might be because it is a
|
|
628
|
+
# namespace package. In this case pick the root path from the
|
|
629
|
+
# first module that is contained in the package.
|
|
630
|
+
if filepath is None:
|
|
631
|
+
raise RuntimeError(
|
|
632
|
+
"No root path can be found for the provided module"
|
|
633
|
+
f" {import_name!r}. This can happen because the module"
|
|
634
|
+
" came from an import hook that does not provide file"
|
|
635
|
+
" name information or because it's a namespace package."
|
|
636
|
+
" In this case the root path needs to be explicitly"
|
|
637
|
+
" provided."
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
# filepath is import_name.py for a module, or __init__.py for a package.
|
|
641
|
+
return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return]
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
@cache
|
|
645
|
+
def _split_blueprint_path(name: str) -> list[str]:
|
|
646
|
+
out: list[str] = [name]
|
|
647
|
+
|
|
648
|
+
if "." in name:
|
|
649
|
+
out.extend(_split_blueprint_path(name.rpartition(".")[0]))
|
|
650
|
+
|
|
651
|
+
return out
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
class _CollectErrors:
|
|
655
|
+
"""A context manager that records and silences an error raised within it.
|
|
656
|
+
Used to run all teardown functions, then raise any errors afterward.
|
|
657
|
+
"""
|
|
658
|
+
|
|
659
|
+
def __init__(self) -> None:
|
|
660
|
+
self.errors: list[BaseException] = []
|
|
661
|
+
|
|
662
|
+
def __enter__(self) -> None:
|
|
663
|
+
pass
|
|
664
|
+
|
|
665
|
+
def __exit__(
|
|
666
|
+
self,
|
|
667
|
+
exc_type: type[BaseException] | None,
|
|
668
|
+
exc_val: BaseException | None,
|
|
669
|
+
exc_tb: TracebackType | None,
|
|
670
|
+
) -> bool:
|
|
671
|
+
if exc_val is not None:
|
|
672
|
+
self.errors.append(exc_val)
|
|
673
|
+
|
|
674
|
+
return True
|
|
675
|
+
|
|
676
|
+
def raise_any(self, message: str) -> None:
|
|
677
|
+
"""Raise if any errors were collected."""
|
|
678
|
+
if self.errors:
|
|
679
|
+
raise BaseExceptionGroup(message, self.errors)
|