Use default send_file max-age consistently.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Prior to this commit, the send_file max-age hook and config were only used for the static file handler. Now they are used when calling helpers.send_file directly.
authored by Ron DuPlain · committed by Ron DuPlain · parent 7c79ce6 · Browse files · 6 files·+88 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+88 added−45 removed
- other:+88 added−45 removed
Provenance
- Commit
26da6a5- Tree
6d69d65- Author
Ron DuPlain <ron.duplain@gmail.com>- Committer
Ron DuPlain <ron.duplain@gmail.com>- Parent
7c79ce6
6 files changed+88 added−45 removed
modified:docs/config.rst+7 added-4 removed
109 unmodified lines110 reject incoming requests with a111 content length greater than this by112 returning a 413 status code.113 ``SEND_FILE_MAX_AGE_DEFAULT``: Default cache control max age to use with114- :meth:`flask.Flask.send_static_file`, in114+ :meth:`~flask.Flask.send_static_file` (the115+ default static file handler) and116+ :func:`~flask.send_file`, in117 seconds. Override this value on a per-file118 basis using the117- :meth:`flask.Flask.get_send_file_options` and118- :meth:`flask.Blueprint.get_send_file_options`119- hooks. Defaults to 43200 (12 hours).119+ :meth:`~flask.Flask.get_send_file_max_age`120+ hook on :class:`~flask.Flask` or121+ :class:`~flask.Blueprint`,122+ respectively. Defaults to 43200 (12 hours).123 ``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will124 not execute the error handlers of HTTP125 exceptions but instead treat the126 exception like any other and bubble it277 unmodified linesmodified:flask/testsuite/blueprints.py+23 added
384 unmodified lines385 386 with flask.Flask(__name__).test_request_context():387 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')388 389+ def test_default_static_cache_timeout(self):390+ app = flask.Flask(__name__)391+ class MyBlueprint(flask.Blueprint):392+ def get_send_file_max_age(self, filename):393+ return 100394+395+ blueprint = MyBlueprint('blueprint', __name__, static_folder='static')396+ app.register_blueprint(blueprint)397+398+ # try/finally, in case other tests use this app for Blueprint tests.399+ max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']400+ try:401+ with app.test_request_context():402+ unexpected_max_age = 3600403+ if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:404+ unexpected_max_age = 7200405+ app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age406+ rv = blueprint.send_static_file('index.html')407+ cc = parse_cache_control_header(rv.headers['Cache-Control'])408+ self.assert_equal(cc.max_age, 100)409+ finally:410+ app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default411+412 def test_templates_list(self):413 from blueprintapp import app414 templates = sorted(app.jinja_env.list_templates())415 self.assert_equal(templates, ['admin/index.html',243 unmodified linesmodified:flask/testsuite/helpers.py+17 added-8 removed
235 unmodified lines236 def test_static_file(self):237 app = flask.Flask(__name__)238 # default cache timeout is 12 hours239 with app.test_request_context():240+ # Test with static file handler.241 rv = app.send_static_file('index.html')242 cc = parse_cache_control_header(rv.headers['Cache-Control'])243 self.assert_equal(cc.max_age, 12 * 60 * 60)244+ # Test again with direct use of send_file utility.245+ rv = flask.send_file('static/index.html')246+ cc = parse_cache_control_header(rv.headers['Cache-Control'])247+ self.assert_equal(cc.max_age, 12 * 60 * 60)248 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600249 with app.test_request_context():250+ # Test with static file handler.251 rv = app.send_static_file('index.html')252 cc = parse_cache_control_header(rv.headers['Cache-Control'])253 self.assert_equal(cc.max_age, 3600)248- # override get_send_file_options with some new values and check them254+ # Test again with direct use of send_file utility.255+ rv = flask.send_file('static/index.html')256+ cc = parse_cache_control_header(rv.headers['Cache-Control'])257+ self.assert_equal(cc.max_age, 3600)258 class StaticFileApp(flask.Flask):250- def get_send_file_options(self, filename):251- opts = super(StaticFileApp, self).get_send_file_options(filename)252- opts['cache_timeout'] = 10253- # this test catches explicit inclusion of the conditional254- # keyword arg in the guts255- opts['conditional'] = True256- return opts259+ def get_send_file_max_age(self, filename):260+ return 10261 app = StaticFileApp(__name__)262 with app.test_request_context():263+ # Test with static file handler.264 rv = app.send_static_file('index.html')265 cc = parse_cache_control_header(rv.headers['Cache-Control'])266 self.assert_equal(cc.max_age, 10)267+ # Test again with direct use of send_file utility.268+ rv = flask.send_file('static/index.html')269+ cc = parse_cache_control_header(rv.headers['Cache-Control'])270+ self.assert_equal(cc.max_age, 10)271 272 273 class LoggingTestCase(FlaskTestCase):274 150 unmodified linesmodified:flask/app.py-6 removed
1039 unmodified lines1040 else:1041 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \1042 .append((code_or_exception, f))1043 1044- def get_send_file_options(self, filename):1045- # Override: Hooks in SEND_FILE_MAX_AGE_DEFAULT config.1046- options = super(Flask, self).get_send_file_options(filename)1047- options['cache_timeout'] = self.config['SEND_FILE_MAX_AGE_DEFAULT']1048- return options1049-1044 @setupmethod1045 def template_filter(self, name=None):1046 """A decorator that is used to register custom template filter.1047 You can specify a name for the filter, otherwise the function632 unmodified linesmodified:flask/helpers.py+32 added-19 removed
404 unmodified lines405 406 407 def send_file(filename_or_fp, mimetype=None, as_attachment=False,408 attachment_filename=None, add_etags=True,409- cache_timeout=60 * 60 * 12, conditional=False):409+ cache_timeout=None, conditional=False):410 """Sends the contents of a file to the client. This will use the411 most efficient method available and configured. By default it will412 try to use the WSGI server's file_wrapper support. Alternatively413 you can set the application's :attr:`~Flask.use_x_sendfile` attribute5 unmodified lines419 to send certain files as attachment (HTML for instance). The mimetype420 guessing requires a `filename` or an `attachment_filename` to be421 provided.422 423- Note `get_send_file_options` in :class:`flask.Flask` hooks the424- ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable to set the default425- cache_timeout.426-423 Please never pass filenames to this function from user sources without424 checking them first. Something like this is usually sufficient to425 avoid security problems::426 11 unmodified lines438 deprecated because it was unreliable. Pass a filename if you are439 able to, otherwise attach an etag yourself. This functionality440 will be removed in Flask 1.0441 442+ .. versionchanged:: 0.9443+ cache_timeout pulls its default from application config, when None.444+445 :param filename_or_fp: the filename of the file to send. This is446 relative to the :attr:`~Flask.root_path` if a447 relative path is specified.448 Alternatively a file object might be provided8 unmodified lines457 :param attachment_filename: the filename for the attachment if it458 differs from the file's filename.459 :param add_etags: set to `False` to disable attaching of etags.460 :param conditional: set to `True` to enable conditional responses.461+462- :param cache_timeout: the timeout in seconds for the headers.462+ :param cache_timeout: the timeout in seconds for the headers. When `None`463+ (default), this value is set by464+ :meth:`~Flask.get_send_file_max_age` of465+ :data:`~flask.current_app`.466 """467 mtime = None468 if isinstance(filename_or_fp, basestring):469 filename = filename_or_fp55 unmodified lines525 if mtime is not None:526 rv.last_modified = int(mtime)527 528 rv.cache_control.public = True529+ if cache_timeout is None:530+ cache_timeout = current_app.get_send_file_max_age(filename)531 if cache_timeout:532 rv.cache_control.max_age = cache_timeout533 rv.expires = int(time() + cache_timeout)534 226 unmodified lines761 if self.template_folder is not None:762 return FileSystemLoader(os.path.join(self.root_path,763 self.template_folder))764 760- def get_send_file_options(self, filename):761- """Provides keyword arguments to send to :func:`send_from_directory`.765+ def get_send_file_max_age(self, filename):766+ """Provides default cache_timeout for the :func:`send_file` functions.767 768+ By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from769+ the configuration of :data:`~flask.current_app`.770+771+ Static file functions such as :func:`send_from_directory` use this772+ function, and :func:`send_file` calls this function on773+ :data:`~flask.current_app` when the given cache_timeout is `None`. If a774+ cache_timeout is given in :func:`send_file`, that timeout is used;775+ otherwise, this method is called.776+777 This allows subclasses to change the behavior when sending files based778 on the filename. For example, to set the cache timeout for .js files765- to 60 seconds (note the options are keywords for :func:`send_file`)::779+ to 60 seconds::780 781 class MyFlask(flask.Flask):768- def get_send_file_options(self, filename):769- options = super(MyFlask, self).get_send_file_options(filename)770- if filename.lower().endswith('.js'):771- options['cache_timeout'] = 60772- options['conditional'] = True773- return options782+ def get_send_file_max_age(self, name):783+ if name.lower().endswith('.js'):784+ return 60785+ return flask.Flask.get_send_file_max_age(self, name)786 787 .. versionadded:: 0.9788 """777- options = {}778- options['cache_timeout'] = current_app.config['SEND_FILE_MAX_AGE_DEFAULT']789+ return current_app.config['SEND_FILE_MAX_AGE_DEFAULT']779- return options790 791 def send_static_file(self, filename):792 """Function used internally to send static files from the static793 folder to the browser.1 unmodified line795 .. versionadded:: 0.5796 """797 if not self.has_static_folder:798 raise RuntimeError('No static folder for this object')799+ # Ensure get_send_file_max_age is called in all cases.800+ # Here, we ensure get_send_file_max_age is called for Blueprints.801+ cache_timeout = self.get_send_file_max_age(filename)802 return send_from_directory(self.static_folder, filename,790- **self.get_send_file_options(filename))803+ cache_timeout=cache_timeout)804 805 def open_resource(self, resource, mode='rb'):806 """Opens a resource from the application's resource folder. To see807 how this works, consider the following folder structure::22 unmodified linesmodified:CHANGES+9 added-8 removed
51 unmodified lines52 also adds support for URL generation without an active request context.53 - View functions can now return a tuple with the first instance being an54 instance of :class:`flask.Response`. This allows for returning55 ``jsonify(error="error msg"), 400`` from a view function.56-- :class:`flask.Flask` now provides a `get_send_file_options` hook for57- subclasses to override behavior of serving static files from Flask when using58- :meth:`flask.Flask.send_static_file` based on keywords in59- :func:`flask.helpers.send_file`. This hook is provided a filename, which for60- example allows changing cache controls by file extension. The default61- max-age for `send_static_file` can be configured through a new62- ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, regardless of whether63- the `get_send_file_options` hook is used.56+- :class:`~flask.Flask` and :class:`~flask.Blueprint` now provide a57+ :meth:`~flask.Flask.get_send_file_max_age` hook for subclasses to override58+ behavior of serving static files from Flask when using59+ :meth:`flask.Flask.send_static_file` (used for the default static file60+ handler) and :func:`~flask.helpers.send_file`. This hook is provided a61+ filename, which for example allows changing cache controls by file extension.62+ The default max-age for `send_file` and static files can be configured63+ through a new ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, which is64+ used in the default `get_send_file_max_age` implementation.65 - Fixed an assumption in sessions implementation which could break message66 flashing on sessions implementations which use external storage.67 - Changed the behavior of tuple return values from functions. They are no68 longer arguments to the response object, they now have a defined meaning.298 unmodified lines