Expose send_file max-age as config value, #433.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Need to add the same hook in a Blueprint, but this is the first such case where we need app.config in the Blueprint.
authored by Ron DuPlain · committed by Ron DuPlain · parent 146088d · Browse files · 6 files·+55 added−14 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+55 added−14 removed
- other:+55 added−14 removed
Provenance
- Commit
d94efc6- Tree
04b5055- Author
Ron DuPlain <ron.duplain@gmail.com>- Committer
Ron DuPlain <ron.duplain@gmail.com>- Parent
146088d
6 files changed+55 added−14 removed
modified:docs/config.rst+8 added-1 removed
105 unmodified lines106 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will107 reject incoming requests with a108 content length greater than this by109 returning a 413 status code.110+``SEND_FILE_MAX_AGE_DEFAULT``: Default cache control max age to use with111+ :meth:`flask.Flask.send_static_file`, in112+ seconds. Override this value on a per-file113+ basis using the114+ :meth:`flask.Flask.get_send_file_options` and115+ :meth:`flask.Blueprint.get_send_file_options`116+ hooks. Defaults to 43200 (12 hours).117 ``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will118 not execute the error handlers of HTTP119 exceptions but instead treat the120 exception like any other and bubble it152 unmodified lines273 DATABASE_URI = 'sqlite://:memory:'274 275 class ProductionConfig(Config):276 DATABASE_URI = 'mysql://user@localhost/foo'270- 277+278 class DevelopmentConfig(Config):279 DEBUG = True280 281 class TestingConfig(Config):110 unmodified linesmodified:flask/testsuite/blueprints.py+14 added
14 unmodified lines15 import unittest16 import warnings17 from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning18 from werkzeug.exceptions import NotFound19+from werkzeug.http import parse_cache_control_header20 from jinja2 import TemplateNotFound21 22 23 # import moduleapp here because it uses deprecated features and we don't333 unmodified lines357 self.assert_equal(rv.data.strip(), 'Admin File')358 rv = c.get('/admin/static/css/test.css')359 self.assert_equal(rv.data.strip(), '/* nested file */')360 361+ # try/finally, in case other tests use this app for Blueprint tests.362+ max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']363+ try:364+ expected_max_age = 3600365+ if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:366+ expected_max_age = 7200367+ app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age368+ rv = c.get('/admin/static/css/test.css')369+ cc = parse_cache_control_header(rv.headers['Cache-Control'])370+ self.assert_equal(cc.max_age, expected_max_age)371+ finally:372+ app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default373+374 with app.test_request_context():375 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),376 '/admin/static/test.txt')377 258 unmodified linesmodified:flask/testsuite/helpers.py+9 added-4 removed
204 unmodified lines205 self.assert_equal(options['filename'], 'index.txt')206 207 def test_static_file(self):208 app = flask.Flask(__name__)209- # default cache timeout is 12 hours (hard-coded)209+ # default cache timeout is 12 hours210 with app.test_request_context():211 rv = app.send_static_file('index.html')212 cc = parse_cache_control_header(rv.headers['Cache-Control'])213 self.assert_equal(cc.max_age, 12 * 60 * 60)214+ app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600215+ with app.test_request_context():216+ rv = app.send_static_file('index.html')217+ cc = parse_cache_control_header(rv.headers['Cache-Control'])218+ self.assert_equal(cc.max_age, 3600)214- # override get_static_file_options with some new values and check them219+ # override get_send_file_options with some new values and check them220 class StaticFileApp(flask.Flask):216- def get_static_file_options(self, filename):217- opts = super(StaticFileApp, self).get_static_file_options(filename)221+ def get_send_file_options(self, filename):222+ opts = super(StaticFileApp, self).get_send_file_options(filename)223 opts['cache_timeout'] = 10224 # this test catches explicit inclusion of the conditional225 # keyword arg in the guts226 opts['conditional'] = True160 unmodified linesmodified:flask/app.py+7 added
247 unmodified lines248 'SESSION_COOKIE_PATH': None,249 'SESSION_COOKIE_HTTPONLY': True,250 'SESSION_COOKIE_SECURE': False,251 'MAX_CONTENT_LENGTH': None,252+ 'SEND_FILE_MAX_AGE_DEFAULT': 12 * 60 * 60, # 12 hours253 'TRAP_BAD_REQUEST_ERRORS': False,254 'TRAP_HTTP_EXCEPTIONS': False255 })256 763 unmodified lines1020 else:1021 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \1022 .append((code_or_exception, f))1023 1024+ def get_send_file_options(self, filename):1025+ # Override: Hooks in SEND_FILE_MAX_AGE_DEFAULT config.1026+ options = super(Flask, self).get_send_file_options(filename)1027+ options['cache_timeout'] = self.config['SEND_FILE_MAX_AGE_DEFAULT']1028+ return options1029+1030 @setupmethod1031 def template_filter(self, name=None):1032 """A decorator that is used to register custom template filter.1033 You can specify a name for the filter, otherwise the function532 unmodified linesmodified:flask/helpers.py+9 added-5 removed
317 unmodified lines318 to send certain files as attachment (HTML for instance). The mimetype319 guessing requires a `filename` or an `attachment_filename` to be320 provided.321 322+ Note `get_send_file_options` in :class:`flask.Flask` hooks the323+ ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable to set the default324+ cache_timeout.325+326 Please never pass filenames to this function from user sources without327 checking them first. Something like this is usually sufficient to328 avoid security problems::329 325 unmodified lines655 if self.template_folder is not None:656 return FileSystemLoader(os.path.join(self.root_path,657 self.template_folder))658 655- def get_static_file_options(self, filename):659+ def get_send_file_options(self, filename):660 """Provides keyword arguments to send to :func:`send_from_directory`.661 662 This allows subclasses to change the behavior when sending files based663 on the filename. For example, to set the cache timeout for .js files664 to 60 seconds (note the options are keywords for :func:`send_file`)::665 666 class MyFlask(flask.Flask):663- def get_static_file_options(self, filename):664- options = super(MyFlask, self).get_static_file_options(filename)667+ def get_send_file_options(self, filename):668+ options = super(MyFlask, self).get_send_file_options(filename)669 if filename.lower().endswith('.js'):670 options['cache_timeout'] = 60671 options['conditional'] = True672 return options673 670- .. versionaded:: 0.9674+ .. versionadded:: 0.9675 """676 return {}677 678 def send_static_file(self, filename):4 unmodified lines683 """684 if not self.has_static_folder:685 raise RuntimeError('No static folder for this object')686 return send_from_directory(self.static_folder, filename,683- **self.get_static_file_options(filename))687+ **self.get_send_file_options(filename))688 689 def open_resource(self, resource, mode='rb'):690 """Opens a resource from the application's resource folder. To see691 how this works, consider the following folder structure::22 unmodified linesmodified:CHANGES+8 added-4 removed
46 unmodified lines47 single template name. On an iterable, the first template found is rendered.48 - View functions can now return a tuple with the first instance being an49 instance of :class:`flask.Response`. This allows for returning50 ``jsonify(error="error msg"), 400`` from a view function.51-- :class:`flask.Flask` now provides a `get_static_file_options` hook for52- subclasses to override behavior of serving static files through Flask,53- optionally by filename, which for example allows changing cache controls by54- file extension.51+- :class:`flask.Flask` now provides a `get_send_file_options` hook for52+ subclasses to override behavior of serving static files from Flask when using53+ :meth:`flask.Flask.send_static_file` based on keywords in54+ :func:`flask.helpers.send_file`. This hook is provided a filename, which for55+ example allows changing cache controls by file extension. The default56+ max-age for `send_static_file` can be configured through a new57+ ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, regardless of whether58+ the `get_send_file_options` hook is used.59 60 61 Version 0.8.162 -------------295 unmodified lines