Flask in debug mode will now complain if views are attached after the first view was handled.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 5ca17c8 · Browse files · 3 files·+60 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+60 added−0 removed
- tests:+22 added−0 removed
- other:+38 added−0 removed
Provenance
- Commit
5500986- Tree
8c2dd5b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
5ca17c8
3 files changed+60 added−0 removed
modified:flask/app.py+35 added
13 unmodified lines14 import sys15 from threading import Lock16 from datetime import timedelta17 from itertools import chain18+from functools import update_wrapper19 20 from werkzeug.datastructures import ImmutableDict21 from werkzeug.routing import Map, Rule22 from werkzeug.exceptions import HTTPException, InternalServerError, \15 unmodified lines38 # a lock used for logger initialization39 _logger_lock = Lock()40 41 42+def setupmethod(f):43+ """Wraps a method so that it performs a check in debug mode if the44+ first request was already handled.45+ """46+ def wrapper_func(self, *args, **kwargs):47+ if self.debug and self._got_first_request:48+ raise AssertionError('A setup function was called after the '49+ 'first request was handled. This usually indicates a bug '50+ 'in the application where a module was not imported '51+ 'and decorators or other functionality was called too late.\n'52+ 'To fix this make sure to import all your view modules, '53+ 'database models and everything related at a central place '54+ 'before the application starts serving requests.')55+ return f(self, *args, **kwargs)56+ return update_wrapper(wrapper_func, f)57+58+59 class Flask(_PackageBoundObject):60 """The flask object implements a WSGI application and acts as the central61 object. It is passed the name of the module or package of the62 application. Once it is created it will act as a central registry for319 unmodified lines382 #: app = Flask(__name__)383 #: app.url_map.converters['list'] = ListConverter384 self.url_map = Map()385 386+ # tracks internally if the application already handled at least one387+ # request.388+ self._got_first_request = False389+390 # register the static folder for the application. Do that even391 # if the folder does not exist. First of all it might be created392 # while the server is running (usually happens during development)393 # but also because google appengine stores static files somewhere269 unmodified lines663 stacklevel=2)664 665 self.register_blueprint(module, **options)666 667+ @setupmethod668 def register_blueprint(self, blueprint, **options):669 """Registers a blueprint on the application.670 671 .. versionadded:: 0.79 unmodified lines681 self.blueprints[blueprint.name] = blueprint682 first_registration = True683 blueprint.register(self, options, first_registration)684 685+ @setupmethod686 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):687 """Connects a URL rule. Works exactly like the :meth:`route`688 decorator. If a view_func is provided it will be registered with the689 endpoint.145 unmodified lines835 self.add_url_rule(rule, None, f, **options)836 return f837 return decorator838 839+ @setupmethod840 def endpoint(self, endpoint):841 """A decorator to register a function as an endpoint.842 Example::843 7 unmodified lines851 self.view_functions[endpoint] = f852 return f853 return decorator854 855+ @setupmethod856 def errorhandler(self, code_or_exception):857 """A decorator that is used to register a function give a given858 error code. Example::859 42 unmodified lines902 .. versionadded:: 0.7903 """904 self._register_error_handler(None, code_or_exception, f)905 906+ @setupmethod907 def _register_error_handler(self, key, code_or_exception, f):908 if isinstance(code_or_exception, HTTPException):909 code_or_exception = code_or_exception.code910 if isinstance(code_or_exception, (int, long)):4 unmodified lines915 else:916 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \917 .append((code_or_exception, f))918 919+ @setupmethod920 def template_filter(self, name=None):921 """A decorator that is used to register custom template filter.922 You can specify a name for the filter, otherwise the function923 name will be used. Example::9 unmodified lines933 self.jinja_env.filters[name or f.__name__] = f934 return f935 return decorator936 937+ @setupmethod938 def before_request(self, f):939 """Registers a function to run before each request."""940 self.before_request_funcs.setdefault(None, []).append(f)941 return f942 943+ @setupmethod944 def after_request(self, f):945 """Register a function to be run after each request. Your function946 must take one parameter, a :attr:`response_class` object and return947 a new response object or the same (see :meth:`process_response`).3 unmodified lines951 """952 self.after_request_funcs.setdefault(None, []).append(f)953 return f954 955+ @setupmethod956 def teardown_request(self, f):957 """Register a function to be run at the end of each request,958 regardless of whether there was an exception or not. These functions959 are executed when the request context is popped, even if not an18 unmodified lines978 """979 self.teardown_request_funcs.setdefault(None, []).append(f)980 return f981 982+ @setupmethod983 def context_processor(self, f):984 """Registers a template context processor function."""985 self.template_context_processors[None].append(f)986 return f987 988+ @setupmethod989 def url_value_preprocessor(self, f):990 """Registers a function as URL value preprocessor for all view991 functions of the application. It's called before the view functions992 are called and can modify the url values provided.993 """994 self.url_value_preprocessors.setdefault(None, []).append(f)995 return f996 997+ @setupmethod998 def url_defaults(self, f):999 """Callback function for URL defaults for all view functions of the1000 application. It's called with the endpoint and values and should1001 update the values passed in place.128 unmodified lines1130 error handling.1131 1132 .. versionadded:: 0.71133 """1134+ self._got_first_request = True1135 try:1136 request_started.send(self)1137 rv = self.preprocess_request()1138 if rv is None:247 unmodified linesmodified:tests/flask_tests.py+22 added
942 unmodified lines943 self.assertEqual(c.get('/de/').data, '/de/about')944 self.assertEqual(c.get('/de/about').data, '/foo')945 self.assertEqual(c.get('/foo').data, '/en/about')946 947+ def test_debug_mode_complains_after_first_request(self):948+ app = flask.Flask(__name__)949+ app.debug = True950+ @app.route('/')951+ def index():952+ return 'Awesome'953+ self.assertEqual(app.test_client().get('/').data, 'Awesome')954+ try:955+ @app.route('/foo')956+ def broken():957+ return 'Meh'958+ except AssertionError, e:959+ self.assert_('A setup function was called' in str(e))960+ else:961+ self.fail('Expected exception')962 963+ app.debug = False964+ @app.route('/foo')965+ def working():966+ return 'Meh'967+ self.assertEqual(app.test_client().get('/foo').data, 'Meh')968+969+970 class JSONTestCase(unittest.TestCase):971 972 def test_json_body_encoding(self):973 app = flask.Flask(__name__)1088 unmodified linesmodified:CHANGES+3 added
16 unmodified lines17 - HTTP exceptions and Bad Request Key Errors can now be trapped so that they18 show up normally in the traceback.19 - Flask in debug mode is now detecting some common problems and tries to20 warn you about them.21+- Flask in debug mode will now complain with an assertion error if a view22+ was attached after the first request was handled. This gives earlier23+ feedback when users forget to import view code ahead of time.24 25 Version 0.7.326 -------------27 238 unmodified lines