Skip to content
Myr

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

3 files+60 added−0 removed

modified:flask/app.py+35 added
13 unmodified lines
14import sys15from threading import Lock16from datetime import timedelta17from itertools import chain18from functools import update_wrapper1920from werkzeug.datastructures import ImmutableDict21from werkzeug.routing import Map, Rule22from werkzeug.exceptions import HTTPException, InternalServerError, \
15 unmodified lines
38# a lock used for logger initialization39_logger_lock = Lock()404142def 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)575859class 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 for
319 unmodified lines
382 #: app = Flask(__name__)383 #: app.url_map.converters['list'] = ListConverter384 self.url_map = Map()385386 # tracks internally if the application already handled at least one387 # request.388 self._got_first_request = False389390 # 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 somewhere
269 unmodified lines
663 stacklevel=2)664665 self.register_blueprint(module, **options)666667 @setupmethod668 def register_blueprint(self, blueprint, **options):669 """Registers a blueprint on the application.670671 .. versionadded:: 0.7
9 unmodified lines
681 self.blueprints[blueprint.name] = blueprint682 first_registration = True683 blueprint.register(self, options, first_registration)684685 @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 lines
835 self.add_url_rule(rule, None, f, **options)836 return f837 return decorator838839 @setupmethod840 def endpoint(self, endpoint):841 """A decorator to register a function as an endpoint.842 Example::843
7 unmodified lines
851 self.view_functions[endpoint] = f852 return f853 return decorator854855 @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 lines
902 .. versionadded:: 0.7903 """904 self._register_error_handler(None, code_or_exception, f)905906 @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 lines
915 else:916 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \917 .append((code_or_exception, f))918919 @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 lines
933 self.jinja_env.filters[name or f.__name__] = f934 return f935 return decorator936937 @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 f942943 @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 lines
951 """952 self.after_request_funcs.setdefault(None, []).append(f)953 return f954955 @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 an
18 unmodified lines
978 """979 self.teardown_request_funcs.setdefault(None, []).append(f)980 return f981982 @setupmethod983 def context_processor(self, f):984 """Registers a template context processor function."""985 self.template_context_processors[None].append(f)986 return f987988 @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 f996997 @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 lines
1130 error handling.11311132 .. 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 lines
modified:tests/flask_tests.py+22 added
942 unmodified lines
943 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')946947 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')962963 app.debug = False964 @app.route('/foo')965 def working():966 return 'Meh'967 self.assertEqual(app.test_client().get('/foo').data, 'Meh')968969970class JSONTestCase(unittest.TestCase):971972 def test_json_body_encoding(self):973 app = flask.Flask(__name__)
1088 unmodified lines
modified:CHANGES+3 added
16 unmodified lines
17- 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.2425Version 0.7.326-------------27
238 unmodified lines