Merge pull request #3828 from pallets/move-send-file
Before adoption: this commit came in with the history the project adopted, so no landing records it.
move send_file and send_from_directory to Werkzeug
authored by David Lord · committed by GitHub · parents 15a49e7, dc11cdb · Browse files · 8 files·+254 added−648 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+254 added−648 removed
- tests:+19 added−331 removed
- other:+235 added−317 removed
Provenance
- Commit
bbb273b- Tree
373f9a9- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
15a49e7- Parent 2
dc11cdb
8 files changed+254 added−648 removed
modified:docs/patterns/fileuploads.rst+17 added-21 removed
61 unmodified lines62 return redirect(request.url)63 if file and allowed_file(file.filename):64 filename = secure_filename(file.filename)65 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))66- return redirect(url_for('uploaded_file',67- filename=filename))66+ return redirect(url_for('download_file', name=filename))67 return '''68 <!doctype html>69 <title>Upload new File</title>70 <h1>Upload new File</h1>29 unmodified lines100 101 >>> secure_filename('../../../../home/username/.bashrc')102 'home_username_.bashrc'103 105-Now one last thing is missing: the serving of the uploaded files. In the106-:func:`upload_file()` we redirect the user to107-``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``.108-So we write the :func:`uploaded_file` function to return the file of that name. As109-of Flask 0.5 we can use a function that does that for us::104+We want to be able to serve the uploaded files so they can be downloaded105+by users. We'll define a ``download_file`` view to serve files in the106+upload folder by name. ``url_for("download_file", name=name)`` generates107+download URLs.108 109+.. code-block:: python110+111 from flask import send_from_directory112 113- @app.route('/uploads/<filename>')114- def uploaded_file(filename):115- return send_from_directory(app.config['UPLOAD_FOLDER'],116- filename)113+ @app.route('/uploads/<name>')114+ def download_file(name):115+ return send_from_directory(app.config["UPLOAD_FOLDER"], name)116 118-Alternatively you can register `uploaded_file` as `build_only` rule and119-use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with120-older versions of Flask::117+If you're using middleware or the HTTP server to serve files, you can118+register the ``download_file`` endpoint as ``build_only`` so ``url_for``119+will work without a view function.120 122- from werkzeug.middleware.shared_data import SharedDataMiddleware123- app.add_url_rule('/uploads/<filename>', 'uploaded_file',124- build_only=True)125- app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {126- '/uploads': app.config['UPLOAD_FOLDER']127- })121+.. code-block:: python122 129-If you now run the application everything should work as expected.123+ app.add_url_rule(124+ "/uploads/<name>", endpoint="download_file", build_only=True125+ )126 127 128 Improving Uploads129 -----------------54 unmodified linesmodified:docs/config.rst+8 added-3 removed
263 unmodified lines264 265 .. py:data:: SEND_FILE_MAX_AGE_DEFAULT266 267 When serving files, set the cache control max age to this number of268- seconds. Can either be a :class:`datetime.timedelta` or an ``int``.268+ seconds. Can be a :class:`datetime.timedelta` or an ``int``.269 Override this value on a per-file basis using270- :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.270+ :meth:`~flask.Flask.get_send_file_max_age` on the application or271+ blueprint.272 272- Default: ``timedelta(hours=12)`` (``43200`` seconds)273+ If ``None``, ``send_file`` tells the browser to use conditional274+ requests will be used instead of a timed cache, which is usually275+ preferable.276 277+ Default: ``None``278+279 .. py:data:: SERVER_NAME280 281 Inform the application what host and port it is bound to. Required282 for subdomain route matching support.486 unmodified linesmodified:src/flask/app.py+14 added-10 removed
53 unmodified lines54 from .wrappers import Response55 56 57 def _make_timedelta(value):58- if not isinstance(value, timedelta):59- return timedelta(seconds=value)60- return value58+ if value is None or isinstance(value, timedelta):59+ return value60 61+ return timedelta(seconds=value)62 63+64 class Flask(Scaffold):65 """The flask object implements a WSGI application and acts as the central66 object. It is passed the name of the module or package of the67 application. Once it is created it will act as a central registry for166 unmodified lines234 permanent_session_lifetime = ConfigAttribute(235 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta236 )237 237- #: A :class:`~datetime.timedelta` which is used as default cache_timeout238- #: for the :func:`send_file` functions. The default is 12 hours.238+ #: A :class:`~datetime.timedelta` or number of seconds which is used239+ #: as the default ``max_age`` for :func:`send_file`. The default is240+ #: ``None``, which tells the browser to use conditional requests241+ #: instead of a timed cache.242 #:240- #: This attribute can also be configured from the config with the241- #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration242- #: variable can also be set with an integer value used as seconds.243- #: Defaults to ``timedelta(hours=12)``243+ #: Configured with the :data:`SEND_FILE_MAX_AGE_DEFAULT`244+ #: configuration key.245+ #:246+ #: .. versionchanged:: 2.0247+ #: Defaults to ``None`` instead of 12 hours.248 send_file_max_age_default = ConfigAttribute(249 "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta250 )251 48 unmodified lines300 "SESSION_COOKIE_SECURE": False,301 "SESSION_COOKIE_SAMESITE": None,302 "SESSION_REFRESH_EACH_REQUEST": True,303 "MAX_CONTENT_LENGTH": None,300- "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),304+ "SEND_FILE_MAX_AGE_DEFAULT": None,305 "TRAP_BAD_REQUEST_ERRORS": None,306 "TRAP_HTTP_EXCEPTIONS": False,307 "EXPLAIN_TEMPLATE_LOADING": False,308 "PREFERRED_URL_SCHEME": "http",1734 unmodified linesmodified:src/flask/helpers.py+182 added-283 removed
1-import io2-import mimetypes1 import os2 import pkgutil5-import posixpath3 import socket4 import sys8-import unicodedata5+import warnings6 from functools import update_wrapper7 from threading import RLock11-from time import time12-from zlib import adler328 9+import werkzeug.utils10 from jinja2 import FileSystemLoader15-from werkzeug.datastructures import Headers16-from werkzeug.exceptions import BadRequest11 from werkzeug.exceptions import NotFound18-from werkzeug.exceptions import RequestedRangeNotSatisfiable12 from werkzeug.routing import BuildError13 from werkzeug.urls import url_quote21-from werkzeug.wsgi import wrap_file14 15 from .globals import _app_ctx_stack16 from .globals import _request_ctx_stack17 from .globals import current_app417 unmodified lines435 return [x[1] for x in flashes]436 return flashes437 438 439+def _prepare_send_file_kwargs(440+ download_name=None,441+ attachment_filename=None,442+ max_age=None,443+ cache_timeout=None,444+ **kwargs,445+):446+ if attachment_filename is not None:447+ warnings.warn(448+ "The 'attachment_filename' parameter has been renamed to 'download_name'."449+ " The old name will be removed in Flask 2.1.",450+ DeprecationWarning,451+ stacklevel=3,452+ )453+ download_name = attachment_filename454+455+ if cache_timeout is not None:456+ warnings.warn(457+ "The 'cache_timeout' parameter has been renamed to 'max_age'. The old name"458+ " will be removed in Flask 2.1.",459+ DeprecationWarning,460+ stacklevel=3,461+ )462+ max_age = cache_timeout463+464+ if max_age is None:465+ max_age = current_app.get_send_file_max_age466+467+ kwargs.update(468+ environ=request.environ,469+ download_name=download_name,470+ max_age=max_age,471+ use_x_sendfile=current_app.use_x_sendfile,472+ response_class=current_app.response_class,473+ _root_path=current_app.root_path,474+ )475+ return kwargs476+477+478 def send_file(448- filename_or_fp,479+ path_or_file,480 mimetype=None,481 as_attachment=False,482+ download_name=None,483 attachment_filename=None,484+ conditional=True,485 add_etags=True,453- cache_timeout=None,454- conditional=False,486 last_modified=None,487+ max_age=None,488+ cache_timeout=None,489 ):457- """Sends the contents of a file to the client. This will use the458- most efficient method available and configured. By default it will459- try to use the WSGI server's file_wrapper support. Alternatively460- you can set the application's :attr:`~Flask.use_x_sendfile` attribute461- to ``True`` to directly emit an ``X-Sendfile`` header. This however462- requires support of the underlying webserver for ``X-Sendfile``.490+ """Send the contents of a file to the client.491 464- By default it will try to guess the mimetype for you, but you can465- also explicitly provide one. For extra security you probably want466- to send certain files as attachment (HTML for instance). The mimetype467- guessing requires a `filename` or an `attachment_filename` to be468- provided.492+ The first argument can be a file path or a file-like object. Paths493+ are preferred in most cases because Werkzeug can manage the file and494+ get extra information from the path. Passing a file-like object495+ requires that the file is opened in binary mode, and is mostly496+ useful when building a file in memory with :class:`io.BytesIO`.497 470- When passing a file-like object instead of a filename, only binary471- mode is supported (``open(filename, "rb")``, :class:`~io.BytesIO`,472- etc.). Text mode files and :class:`~io.StringIO` will raise a473- :exc:`ValueError`.498+ Never pass file paths provided by a user. The path is assumed to be499+ trusted, so a user could craft a path to access a file you didn't500+ intend. Use :func:`send_from_directory` to safely serve501+ user-requested paths from within a directory.502 475- ETags will also be attached automatically if a `filename` is provided. You476- can turn this off by setting `add_etags=False`.503+ If the WSGI server sets a ``file_wrapper`` in ``environ``, it is504+ used, otherwise Werkzeug's built-in wrapper is used. Alternatively,505+ if the HTTP server supports ``X-Sendfile``, configuring Flask with506+ ``USE_X_SENDFILE = True`` will tell the server to send the given507+ path, which is much more efficient than reading it in Python.508 478- If `conditional=True` and `filename` is provided, this method will try to479- upgrade the response stream to support range requests. This will allow480- the request to be answered with partial content response.509+ :param path_or_file: The path to the file to send, relative to the510+ current working directory if a relative path is given.511+ Alternatively, a file-like object opened in binary mode. Make512+ sure the file pointer is seeked to the start of the data.513+ :param mimetype: The MIME type to send for the file. If not514+ provided, it will try to detect it from the file name.515+ :param as_attachment: Indicate to a browser that it should offer to516+ save the file instead of displaying it.517+ :param download_name: The default name browsers will use when saving518+ the file. Defaults to the passed file name.519+ :param conditional: Enable conditional and range responses based on520+ request headers. Requires passing a file path and ``environ``.521+ :param add_etags: Calculate an ETag for the file. Requires passing a522+ file path.523+ :param last_modified: The last modified time to send for the file,524+ in seconds. If not provided, it will try to detect it from the525+ file path.526+ :param max_age: How long the client should cache the file, in527+ seconds. If set, ``Cache-Control`` will be ``public``, otherwise528+ it will be ``no-cache`` to prefer conditional caching.529 482- Please never pass filenames to this function from user sources;483- you should use :func:`send_from_directory` instead.530+ .. versionchanged:: 2.0531+ ``download_name`` replaces the ``attachment_filename``532+ parameter. If ``as_attachment=False``, it is passed with533+ ``Content-Disposition: inline`` instead.534 535 .. versionchanged:: 2.0536+ ``max_age`` replaces the ``cache_timeout`` parameter.537+ ``conditional`` is enabled and ``max_age`` is not set by538+ default.539+540+ .. versionchanged:: 2.0541 Passing a file-like object that inherits from542 :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather543 than sending an empty file.544 545+ .. versionadded:: 2.0546+ Moved the implementation to Werkzeug. This is now a wrapper to547+ pass some Flask-specific arguments.548+549 .. versionchanged:: 1.1550 ``filename`` may be a :class:`~os.PathLike` object.551 552 .. versionchanged:: 1.13 unmodified lines556 Filenames are encoded with ASCII instead of Latin-1 for broader557 compatibility with WSGI servers.558 559 .. versionchanged:: 1.0501- UTF-8 filenames, as specified in `RFC 2231`_, are supported.560+ UTF-8 filenames as specified in :rfc:`2231` are supported.561 503- .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4504-562 .. versionchanged:: 0.12506- The filename is no longer automatically inferred from file507- objects. If you want to use automatic MIME and etag support, pass508- a filename via ``filename_or_fp`` or ``attachment_filename``.563+ The filename is no longer automatically inferred from file564+ objects. If you want to use automatic MIME and etag support,565+ pass a filename via ``filename_or_fp`` or566+ ``attachment_filename``.567 568 .. versionchanged:: 0.12511- ``attachment_filename`` is preferred over ``filename`` for MIME512- detection.569+ ``attachment_filename`` is preferred over ``filename`` for MIME570+ detection.571 572 .. versionchanged:: 0.9515- ``cache_timeout`` defaults to516- :meth:`Flask.get_send_file_max_age`.573+ ``cache_timeout`` defaults to574+ :meth:`Flask.get_send_file_max_age`.575 576 .. versionchanged:: 0.7519- MIME guessing and etag support for file-like objects was520- deprecated because it was unreliable. Pass a filename if you are521- able to, otherwise attach an etag yourself. This functionality522- will be removed in Flask 1.0.577+ MIME guessing and etag support for file-like objects was578+ deprecated because it was unreliable. Pass a filename if you are579+ able to, otherwise attach an etag yourself.580 524- .. versionadded:: 0.5525- The ``add_etags``, ``cache_timeout`` and ``conditional``526- parameters were added. The default behavior is to add etags.581+ .. versionchanged:: 0.5582+ The ``add_etags``, ``cache_timeout`` and ``conditional``583+ parameters were added. The default behavior is to add etags.584 585 .. versionadded:: 0.2529-530- :param filename_or_fp: The filename of the file to send, relative to531- :attr:`~Flask.root_path` if a relative path is specified.532- Alternatively, a file-like object opened in binary mode. Make533- sure the file pointer is seeked to the start of the data.534- ``X-Sendfile`` will only be used with filenames.535- :param mimetype: the mimetype of the file if provided. If a file path is536- given, auto detection happens as fallback, otherwise an537- error will be raised.538- :param as_attachment: set to ``True`` if you want to send this file with539- a ``Content-Disposition: attachment`` header.540- :param attachment_filename: the filename for the attachment if it541- differs from the file's filename.542- :param add_etags: set to ``False`` to disable attaching of etags.543- :param conditional: set to ``True`` to enable conditional responses.544-545- :param cache_timeout: the timeout in seconds for the headers. When ``None``546- (default), this value is set by547- :meth:`~Flask.get_send_file_max_age` of548- :data:`~flask.current_app`.549- :param last_modified: set the ``Last-Modified`` header to this value,550- a :class:`~datetime.datetime` or timestamp.551- If a file was passed, this overrides its mtime.586 """553- mtime = None554- fsize = None555-556- if hasattr(filename_or_fp, "__fspath__"):557- filename_or_fp = os.fspath(filename_or_fp)558-559- if isinstance(filename_or_fp, str):560- filename = filename_or_fp561- if not os.path.isabs(filename):562- filename = os.path.join(current_app.root_path, filename)563- file = None564- if attachment_filename is None:565- attachment_filename = os.path.basename(filename)566- else:567- file = filename_or_fp568- filename = None569-570- if mimetype is None:571- if attachment_filename is not None:572- mimetype = (573- mimetypes.guess_type(attachment_filename)[0]574- or "application/octet-stream"575- )576-577- if mimetype is None:578- raise ValueError(579- "Unable to infer MIME-type because no filename is available. "580- "Please set either `attachment_filename`, pass a filepath to "581- "`filename_or_fp` or set your own MIME-type via `mimetype`."582- )583-584- headers = Headers()585- if as_attachment:586- if attachment_filename is None:587- raise TypeError("filename unavailable, required for sending as attachment")588-589- if not isinstance(attachment_filename, str):590- attachment_filename = attachment_filename.decode("utf-8")591-592- try:593- attachment_filename = attachment_filename.encode("ascii")594- except UnicodeEncodeError:595- quoted = url_quote(attachment_filename, safe="")596- filenames = {597- "filename": unicodedata.normalize("NFKD", attachment_filename).encode(598- "ascii", "ignore"599- ),600- "filename*": f"UTF-8''{quoted}",601- }602- else:603- filenames = {"filename": attachment_filename}604-605- headers.add("Content-Disposition", "attachment", **filenames)606-607- if current_app.use_x_sendfile and filename:608- if file is not None:609- file.close()610-611- headers["X-Sendfile"] = filename612- fsize = os.path.getsize(filename)613- data = None614- else:615- if file is None:616- file = open(filename, "rb")617- mtime = os.path.getmtime(filename)618- fsize = os.path.getsize(filename)619- elif isinstance(file, io.BytesIO):620- fsize = file.getbuffer().nbytes621- elif isinstance(file, io.TextIOBase):622- raise ValueError("Files must be opened in binary mode or use BytesIO.")623-624- data = wrap_file(request.environ, file)625-626- if fsize is not None:627- headers["Content-Length"] = fsize628-629- rv = current_app.response_class(630- data, mimetype=mimetype, headers=headers, direct_passthrough=True587+ return werkzeug.utils.send_file(588+ **_prepare_send_file_kwargs(589+ path_or_file=path_or_file,590+ environ=request.environ,591+ mimetype=mimetype,592+ as_attachment=as_attachment,593+ download_name=download_name,594+ attachment_filename=attachment_filename,595+ conditional=conditional,596+ add_etags=add_etags,597+ last_modified=last_modified,598+ max_age=max_age,599+ cache_timeout=cache_timeout,600+ )601 )602 633- if last_modified is not None:634- rv.last_modified = last_modified635- elif mtime is not None:636- rv.last_modified = mtime603 638- rv.cache_control.public = True639- if cache_timeout is None:640- cache_timeout = current_app.get_send_file_max_age(filename)641- if cache_timeout is not None:642- rv.cache_control.max_age = cache_timeout643- rv.expires = int(time() + cache_timeout)644-645- if add_etags and filename is not None:646- from warnings import warn647-648- try:649- check = (650- adler32(651- filename.encode("utf-8") if isinstance(filename, str) else filename652- )653- & 0xFFFFFFFF654- )655- rv.set_etag(656- f"{os.path.getmtime(filename)}-{os.path.getsize(filename)}-{check}"657- )658- except OSError:659- warn(660- f"Access {filename} failed, maybe it does not exist, so"661- " ignore etags in headers",662- stacklevel=2,663- )664-665- if conditional:666- try:667- rv = rv.make_conditional(request, accept_ranges=True, complete_length=fsize)668- except RequestedRangeNotSatisfiable:669- if file is not None:670- file.close()671- raise672- # make sure we don't send x-sendfile for servers that673- # ignore the 304 status code for x-sendfile.674- if rv.status_code == 304:675- rv.headers.pop("x-sendfile", None)676- return rv677-678-604 def safe_join(directory, *pathnames):680- """Safely join `directory` and zero or more untrusted `pathnames`681- components.605+ """Safely join zero or more untrusted path components to a base606+ directory to avoid escaping the base directory.607 683- Example usage::684-685- @app.route('/wiki/<path:filename>')686- def wiki_page(filename):687- filename = safe_join(app.config['WIKI_FOLDER'], filename)688- with open(filename, 'rb') as fd:689- content = fd.read() # Read and process the file content...690-691- :param directory: the trusted base directory.692- :param pathnames: the untrusted pathnames relative to that directory.693- :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed694- paths fall out of its boundaries.608+ :param directory: The trusted base directory.609+ :param pathnames: The untrusted path components relative to the610+ base directory.611+ :return: A safe path, otherwise ``None``.612 """613+ warnings.warn(614+ "'flask.helpers.safe_join' is deprecated and will be removed in"615+ " 2.1. Use 'werkzeug.utils.safe_join' instead.",616+ DeprecationWarning,617+ stacklevel=2,618+ )619+ path = werkzeug.utils.safe_join(directory, *pathnames)620 697- parts = [directory]621+ if path is None:622+ raise NotFound()623 699- for filename in pathnames:700- if filename != "":701- filename = posixpath.normpath(filename)624+ return path625 703- if (704- any(sep in filename for sep in _os_alt_seps)705- or os.path.isabs(filename)706- or filename == ".."707- or filename.startswith("../")708- ):709- raise NotFound()626 711- parts.append(filename)627+def send_from_directory(directory, path, **kwargs):628+ """Send a file from within a directory using :func:`send_file`.629 713- return posixpath.join(*parts)630+ .. code-block:: python631 632+ @app.route("/uploads/<path:name>")633+ def download_file(name):634+ return send_from_directory(635+ app.config['UPLOAD_FOLDER'], name, as_attachment=True636+ )637 716-def send_from_directory(directory, filename, **options):717- """Send a file from a given directory with :func:`send_file`. This718- is a secure way to quickly expose static files from an upload folder719- or something similar.638+ This is a secure way to serve files from a folder, such as static639+ files or uploads. Uses :func:`~werkzeug.security.safe_join` to640+ ensure the path coming from the client is not maliciously crafted to641+ point outside the specified directory.642 721- Example usage::643+ If the final path does not point to an existing regular file,644+ raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.645 723- @app.route('/uploads/<path:filename>')724- def download_file(filename):725- return send_from_directory(app.config['UPLOAD_FOLDER'],726- filename, as_attachment=True)646+ :param directory: The directory that ``path`` must be located under.647+ :param path: The path to the file to send, relative to648+ ``directory``.649+ :param kwargs: Arguments to pass to :func:`send_file`.650 728- .. admonition:: Sending files and Performance651+ .. versionadded:: 2.0652+ Moved the implementation to Werkzeug. This is now a wrapper to653+ pass some Flask-specific arguments.654 730- It is strongly recommended to activate either ``X-Sendfile`` support in731- your webserver or (if no authentication happens) to tell the webserver732- to serve files for the given path on its own without calling into the733- web application for improved performance.734-655 .. versionadded:: 0.5736-737- :param directory: the directory where all the files are stored.738- :param filename: the filename relative to that directory to739- download.740- :param options: optional keyword arguments that are directly741- forwarded to :func:`send_file`.656 """743- filename = os.fspath(filename)744- directory = os.fspath(directory)745- filename = safe_join(directory, filename)746- if not os.path.isabs(filename):747- filename = os.path.join(current_app.root_path, filename)748- try:749- if not os.path.isfile(filename):750- raise NotFound()751- except (TypeError, ValueError):752- raise BadRequest()753- options.setdefault("conditional", True)754- return send_file(filename, **options)657+ return werkzeug.utils.send_from_directory(658+ directory, path, **_prepare_send_file_kwargs(**kwargs)659+ )660 661 662 def get_root_path(import_name):663 """Returns the path to a package or cwd if that cannot be found. This256 unmodified lines920 if self.template_folder is not None:921 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))922 923 def get_send_file_max_age(self, filename):1019- """Provides default cache_timeout for the :func:`send_file` functions.924+ """Used by :func:`send_file` to determine the ``max_age`` cache925+ value for a given file path if it wasn't passed.926 1021- By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from1022- the configuration of :data:`~flask.current_app`.927+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from928+ the configuration of :data:`~flask.current_app`. This defaults929+ to ``None``, which tells the browser to use conditional requests930+ instead of a timed cache, which is usually preferable.931 1024- Static file functions such as :func:`send_from_directory` use this1025- function, and :func:`send_file` calls this function on1026- :data:`~flask.current_app` when the given cache_timeout is ``None``. If a1027- cache_timeout is given in :func:`send_file`, that timeout is used;1028- otherwise, this method is called.932+ .. versionchanged:: 2.0933+ The default configuration is ``None`` instead of 12 hours.934 1030- This allows subclasses to change the behavior when sending files based1031- on the filename. For example, to set the cache timeout for .js files1032- to 60 seconds::1033-1034- class MyFlask(flask.Flask):1035- def get_send_file_max_age(self, name):1036- if name.lower().endswith('.js'):1037- return 601038- return flask.Flask.get_send_file_max_age(self, name)1039-935 .. versionadded:: 0.9936 """1042- return total_seconds(current_app.send_file_max_age_default)937+ value = current_app.send_file_max_age_default938 939+ if value is None:940+ return None941+942+ return total_seconds(value)943+944 def send_static_file(self, filename):945 """Function used internally to send static files from the static946 folder to the browser.947 948 .. versionadded:: 0.5949 """950 if not self.has_static_folder:951 raise RuntimeError("No static folder for this object")1052- # Ensure get_send_file_max_age is called in all cases.1053- # Here, we ensure get_send_file_max_age is called for Blueprints.1054- cache_timeout = self.get_send_file_max_age(filename)1055- return send_from_directory(1056- self.static_folder, filename, cache_timeout=cache_timeout1057- )952 953+ # send_file only knows to call get_send_file_max_age on the app,954+ # call it here so it works for blueprints too.955+ max_age = self.get_send_file_max_age(filename)956+ return send_from_directory(self.static_folder, filename, max_age=max_age)957+958 def open_resource(self, resource, mode="rb"):959 """Opens a resource from the application's resource folder. To see960 how this works, consider the following folder structure::961 55 unmodified linesmodified:tests/test_blueprints.py+1 added-1 removed
220 unmodified lines221 with flask.Flask(__name__).test_request_context():222 assert flask.render_template("nested/nested.txt") == "I'm nested"223 224 225-def test_default_static_cache_timeout(app):225+def test_default_static_max_age(app):226 class MyBlueprint(flask.Blueprint):227 def get_send_file_max_age(self, filename):228 return 100229 623 unmodified linesmodified:tests/test_helpers.py+18 added-322 removed
1-import datetime1 import io2 import os4-import sys3 4 import pytest7-from werkzeug.datastructures import Range8-from werkzeug.exceptions import BadRequest9-from werkzeug.exceptions import NotFound10-from werkzeug.http import http_date11-from werkzeug.http import parse_cache_control_header12-from werkzeug.http import parse_options_header5 6 import flask7 from flask.helpers import get_debug_flag8 from flask.helpers import get_env21 unmodified lines30 return getattr(self._io, name)31 32 33 class TestSendfile:42- def test_send_file_regular(self, app, req_ctx):34+ def test_send_file(self, app, req_ctx):35 rv = flask.send_file("static/index.html")36 assert rv.direct_passthrough37 assert rv.mimetype == "text/html"46- with app.open_resource("static/index.html") as f:47- rv.direct_passthrough = False48- assert rv.data == f.read()49- rv.close()38 51- def test_send_file_xsendfile(self, app, req_ctx):52- app.use_x_sendfile = True53- rv = flask.send_file("static/index.html")54- assert rv.direct_passthrough55- assert "x-sendfile" in rv.headers56- assert rv.headers["x-sendfile"] == os.path.join(57- app.root_path, "static/index.html"58- )59- assert rv.mimetype == "text/html"60- rv.close()61-62- def test_send_file_last_modified(self, app, client):63- last_modified = datetime.datetime(1999, 1, 1)64-65- @app.route("/")66- def index():67- return flask.send_file(68- io.BytesIO(b"party like it's"),69- last_modified=last_modified,70- mimetype="text/plain",71- )72-73- rv = client.get("/")74- assert rv.last_modified == last_modified75-76- def test_send_file_object_without_mimetype(self, app, req_ctx):77- with pytest.raises(ValueError) as excinfo:78- flask.send_file(io.BytesIO(b"LOL"))79- assert "Unable to infer MIME-type" in str(excinfo.value)80- assert "no filename is available" in str(excinfo.value)81-82- flask.send_file(io.BytesIO(b"LOL"), attachment_filename="filename")83-84- @pytest.mark.parametrize(85- "opener",86- [87- lambda app: open(os.path.join(app.static_folder, "index.html"), "rb"),88- lambda app: io.BytesIO(b"Test"),89- lambda app: PyBytesIO(b"Test"),90- ],91- )92- @pytest.mark.usefixtures("req_ctx")93- def test_send_file_object(self, app, opener):94- file = opener(app)95- app.use_x_sendfile = True96- rv = flask.send_file(file, mimetype="text/plain")97- rv.direct_passthrough = False98- assert rv.data99- assert rv.mimetype == "text/plain"100- assert "x-sendfile" not in rv.headers101- rv.close()102-103- @pytest.mark.parametrize(104- "opener",105- [106- lambda app: io.StringIO("Test"),107- lambda app: open(os.path.join(app.static_folder, "index.html")),108- ],109- )110- @pytest.mark.usefixtures("req_ctx")111- def test_send_file_text_fails(self, app, opener):112- file = opener(app)113-114- with pytest.raises(ValueError):115- flask.send_file(file, mimetype="text/plain")116-117- file.close()118-119- def test_send_file_pathlike(self, app, req_ctx):120- rv = flask.send_file(FakePath("static/index.html"))121- assert rv.direct_passthrough122- assert rv.mimetype == "text/html"39 with app.open_resource("static/index.html") as f:40 rv.direct_passthrough = False41 assert rv.data == f.read()126- rv.close()42 128- @pytest.mark.skipif(129- not callable(getattr(Range, "to_content_range_header", None)),130- reason="not implemented within werkzeug",131- )132- def test_send_file_range_request(self, app, client):133- @app.route("/")134- def index():135- return flask.send_file("static/index.html", conditional=True)136-137- rv = client.get("/", headers={"Range": "bytes=4-15"})138- assert rv.status_code == 206139- with app.open_resource("static/index.html") as f:140- assert rv.data == f.read()[4:16]43 rv.close()44 143- rv = client.get("/", headers={"Range": "bytes=4-"})144- assert rv.status_code == 206145- with app.open_resource("static/index.html") as f:146- assert rv.data == f.read()[4:]147- rv.close()148-149- rv = client.get("/", headers={"Range": "bytes=4-1000"})150- assert rv.status_code == 206151- with app.open_resource("static/index.html") as f:152- assert rv.data == f.read()[4:]153- rv.close()154-155- rv = client.get("/", headers={"Range": "bytes=-10"})156- assert rv.status_code == 206157- with app.open_resource("static/index.html") as f:158- assert rv.data == f.read()[-10:]159- rv.close()160-161- rv = client.get("/", headers={"Range": "bytes=1000-"})162- assert rv.status_code == 416163- rv.close()164-165- rv = client.get("/", headers={"Range": "bytes=-"})166- assert rv.status_code == 416167- rv.close()168-169- rv = client.get("/", headers={"Range": "somethingsomething"})170- assert rv.status_code == 416171- rv.close()172-173- last_modified = datetime.datetime.utcfromtimestamp(174- os.path.getmtime(os.path.join(app.root_path, "static/index.html"))175- ).replace(microsecond=0)176-177- rv = client.get(178- "/", headers={"Range": "bytes=4-15", "If-Range": http_date(last_modified)}179- )180- assert rv.status_code == 206181- rv.close()182-183- rv = client.get(184- "/",185- headers={186- "Range": "bytes=4-15",187- "If-Range": http_date(datetime.datetime(1999, 1, 1)),188- },189- )190- assert rv.status_code == 200191- rv.close()192-193- def test_send_file_range_request_bytesio(self, app, client):194- @app.route("/")195- def index():196- file = io.BytesIO(b"somethingsomething")197- return flask.send_file(198- file, attachment_filename="filename", conditional=True199- )200-201- rv = client.get("/", headers={"Range": "bytes=4-15"})202- assert rv.status_code == 206203- assert rv.data == b"somethingsomething"[4:16]204- rv.close()205-206- def test_send_file_range_request_xsendfile_invalid(self, app, client):207- # https://github.com/pallets/flask/issues/2526208- app.use_x_sendfile = True209-210- @app.route("/")211- def index():212- return flask.send_file("static/index.html", conditional=True)213-214- rv = client.get("/", headers={"Range": "bytes=1000-"})215- assert rv.status_code == 416216- rv.close()217-218- def test_attachment(self, app, req_ctx):219- app = flask.Flask(__name__)220- with app.test_request_context():221- with open(os.path.join(app.root_path, "static/index.html"), "rb") as f:222- rv = flask.send_file(223- f, as_attachment=True, attachment_filename="index.html"224- )225- value, options = parse_options_header(rv.headers["Content-Disposition"])226- assert value == "attachment"227- rv.close()228-229- with open(os.path.join(app.root_path, "static/index.html"), "rb") as f:230- rv = flask.send_file(231- f, as_attachment=True, attachment_filename="index.html"232- )233- value, options = parse_options_header(rv.headers["Content-Disposition"])234- assert value == "attachment"235- assert options["filename"] == "index.html"236- assert "filename*" not in rv.headers["Content-Disposition"]237- rv.close()238-239- rv = flask.send_file("static/index.html", as_attachment=True)240- value, options = parse_options_header(rv.headers["Content-Disposition"])241- assert value == "attachment"242- assert options["filename"] == "index.html"243- rv.close()244-245- rv = flask.send_file(246- io.BytesIO(b"Test"),247- as_attachment=True,248- attachment_filename="index.txt",249- add_etags=False,250- )251- assert rv.mimetype == "text/plain"252- value, options = parse_options_header(rv.headers["Content-Disposition"])253- assert value == "attachment"254- assert options["filename"] == "index.txt"255- rv.close()256-257- @pytest.mark.usefixtures("req_ctx")258- @pytest.mark.parametrize(259- ("filename", "ascii", "utf8"),260- (261- ("index.html", "index.html", False),262- (263- "Ñandú/pingüino.txt",264- '"Nandu/pinguino.txt"',265- "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",266- ),267- ("Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),268- # ":/" are not safe in filename* value269- ("те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"),270- ),271- )272- def test_attachment_filename_encoding(self, filename, ascii, utf8):273- rv = flask.send_file(274- "static/index.html", as_attachment=True, attachment_filename=filename275- )276- rv.close()277- content_disposition = rv.headers["Content-Disposition"]278- assert f"filename={ascii}" in content_disposition279- if utf8:280- assert f"filename*=UTF-8''{utf8}" in content_disposition281- else:282- assert "filename*=UTF-8''" not in content_disposition283-45 def test_static_file(self, app, req_ctx):285- # default cache timeout is 12 hours46+ # Default max_age is None.47 48 # Test with static file handler.49 rv = app.send_static_file("index.html")289- cc = parse_cache_control_header(rv.headers["Cache-Control"])290- assert cc.max_age == 12 * 60 * 6050+ assert rv.cache_control.max_age is None51 rv.close()292- # Test again with direct use of send_file utility.52+53+ # Test with direct use of send_file.54 rv = flask.send_file("static/index.html")294- cc = parse_cache_control_header(rv.headers["Cache-Control"])295- assert cc.max_age == 12 * 60 * 6055+ assert rv.cache_control.max_age is None56 rv.close()57+58 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 360059 60 # Test with static file handler.61 rv = app.send_static_file("index.html")301- cc = parse_cache_control_header(rv.headers["Cache-Control"])302- assert cc.max_age == 360062+ assert rv.cache_control.max_age == 360063 rv.close()304- # Test again with direct use of send_file utility.64+65+ # Test with direct use of send_file.66 rv = flask.send_file("static/index.html")306- cc = parse_cache_control_header(rv.headers["Cache-Control"])307- assert cc.max_age == 360067+ assert rv.cache_control.max_age == 360068 rv.close()69 310- # Test with static file handler.70+ # Test with pathlib.Path.71 rv = app.send_static_file(FakePath("index.html"))312- cc = parse_cache_control_header(rv.headers["Cache-Control"])313- assert cc.max_age == 360072+ assert rv.cache_control.max_age == 360073 rv.close()74 75 class StaticFileApp(flask.Flask):76 def get_send_file_max_age(self, filename):77 return 1078 79 app = StaticFileApp(__name__)80+81 with app.test_request_context():82 # Test with static file handler.83 rv = app.send_static_file("index.html")324- cc = parse_cache_control_header(rv.headers["Cache-Control"])325- assert cc.max_age == 1084+ assert rv.cache_control.max_age == 1085 rv.close()327- # Test again with direct use of send_file utility.86+87+ # Test with direct use of send_file.88 rv = flask.send_file("static/index.html")329- cc = parse_cache_control_header(rv.headers["Cache-Control"])330- assert cc.max_age == 1089+ assert rv.cache_control.max_age == 1090 rv.close()91 92 def test_send_from_directory(self, app, req_ctx):93 app.root_path = os.path.join(3 unmodified lines97 rv.direct_passthrough = False98 assert rv.data.strip() == b"Hello Subdomain"99 rv.close()100 342- def test_send_from_directory_pathlike(self, app, req_ctx):343- app.root_path = os.path.join(344- os.path.dirname(__file__), "test_apps", "subdomaintestmodule"345- )346- rv = flask.send_from_directory(FakePath("static"), FakePath("hello.txt"))347- rv.direct_passthrough = False348- assert rv.data.strip() == b"Hello Subdomain"349- rv.close()101 351- def test_send_from_directory_null_character(self, app, req_ctx):352- app.root_path = os.path.join(353- os.path.dirname(__file__), "test_apps", "subdomaintestmodule"354- )355-356- if sys.version_info >= (3, 8):357- exception = NotFound358- else:359- exception = BadRequest360-361- with pytest.raises(exception):362- flask.send_from_directory("static", "bad\x00")363-364-102 class TestUrlFor:103 def test_url_for_with_anchor(self, app, req_ctx):104 @app.route("/")105 def index():144 unmodified lines250 rv = client.get("/")251 assert rv.data == b"flask"252 253 517-class TestSafeJoin:518- @pytest.mark.parametrize(519- "args, expected",520- (521- (("a/b/c",), "a/b/c"),522- (("/", "a/", "b/", "c/"), "/a/b/c"),523- (("a", "b", "c"), "a/b/c"),524- (("/a", "b/c"), "/a/b/c"),525- (("a/b", "X/../c"), "a/b/c"),526- (("/a/b", "c/X/.."), "/a/b/c"),527- # If last path is '' add a slash528- (("/a/b/c", ""), "/a/b/c/"),529- # Preserve dot slash530- (("/a/b/c", "./"), "/a/b/c/."),531- (("a/b/c", "X/.."), "a/b/c/."),532- # Base directory is always considered safe533- (("../", "a/b/c"), "../a/b/c"),534- (("/..",), "/.."),535- ),536- )537- def test_safe_join(self, args, expected):538- assert flask.safe_join(*args) == expected539-540- @pytest.mark.parametrize(541- "args",542- (543- # path.isabs and ``..'' checks544- ("/a", "b", "/c"),545- ("/a", "../b/c"),546- ("/a", "..", "b/c"),547- # Boundaries violations after path normalization548- ("/a", "b/../b/../../c"),549- ("/a", "b", "c/../.."),550- ("/a", "b/../../c"),551- ),552- )553- def test_safe_join_exceptions(self, args):554- with pytest.raises(NotFound):555- print(flask.safe_join(*args))556-557-254 class TestHelpers:255 @pytest.mark.parametrize(256 "debug, expected_flag, expected_default_flag",257 [56 unmodified linesmodified:tests/test_regression.py-8 removed
1 unmodified line2 import platform3 import threading4 5 import pytest6-from werkzeug.exceptions import NotFound6 7 import flask8 9 _gc_lock = threading.Lock()44 unmodified lines54 for _x in range(10):55 fire()56 57 59-def test_safe_join_toplevel_pardir():60- from flask.helpers import safe_join61-62- with pytest.raises(NotFound):63- safe_join("/foo", "..")64-65-58 def test_aborting(app):59 class Foo(Exception):60 whatever = 4261 17 unmodified linesmodified:CHANGES.rst+14 added
43 unmodified lines44 :issue:`3215`45 - Include ``samesite`` and ``secure`` options when removing the46 session cookie. :pr:`3726`47 - Support passing a ``pathlib.Path`` to ``static_folder``. :pr:`3579`48+- ``send_file`` and ``send_from_directory`` are wrappers around the49+ implementations in ``werkzeug.utils``. :pr:`3828`50+- Some ``send_file`` parameters have been renamed, the old names are51+ deprecated. ``attachment_filename`` is renamed to ``download_name``.52+ ``cache_timeout`` is renamed to ``max_age``. :pr:`3828`53+- ``send_file`` passes ``download_name`` even if54+ ``as_attachment=False`` by using ``Content-Disposition: inline``.55+ :pr:`3828`56+- ``send_file`` sets ``conditional=True`` and ``max_age=None`` by57+ default. ``Cache-Control`` is set to ``no-cache`` if ``max_age`` is58+ not set, otherwise ``public``. This tells browsers to validate59+ conditional requests instead of using a timed cache. :pr:`3828`60+- ``helpers.safe_join`` is deprecated. Use61+ ``werkzeug.utils.safe_join`` instead. :pr:`3828`62 63 64 Version 1.1.265 -------------1011 unmodified lines