diff --git a/docs/api.rst b/docs/api.rst index c9bb1a85..48f753c4 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -272,7 +272,16 @@ thing, like it does for :class:`request` and :class:`session`. Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if - only the application context is bound and not yet a request. + only the application context is bound and not yet a request. This + is especially useful when combined with the :ref:`faking-resources` + pattern for testing. + + Additionally as of 0.10 you can use the subscription operator syntax to + get an attribute or `None` if it's not set. These two usages are now + equivalent:: + + user = getattr(flask.g, 'user', None) + user = flask.g['user'] This is a proxy. See :ref:`notes-on-proxies` for more information. diff --git a/docs/testing.rst b/docs/testing.rst index e87fb9ba..d31be217 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -250,6 +250,7 @@ requires that you pass it a response object:: This in general is less useful because at that point you can directly start using the test client. +.. _faking-resources: Faking Resources and Context ---------------------------- diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 70ea772d..de90bb65 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -1116,6 +1116,19 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(len(errors), 3) self.assert_equal(errors[1], None) + def test_subscript_syntax_on_g(self): + app = flask.Flask(__name__) + app.testing = True + + with app.app_context(): + self.assert_equal(flask.g['x'], None) + flask.g.x = 42 + self.assert_equal(flask.g['x'], 42) + self.assert_equal(flask.g.x, 42) + flask.g['x'] = 23 + self.assert_equal(flask.g['x'], 23) + self.assert_equal(flask.g.x, 23) + class SubdomainTestCase(FlaskTestCase):