Skip to content

Commit 33bae1a

Browse files
committed
Add Flask.request_globals_class to customize g.
Requested by toothr on #pocoo.
1 parent 26da6a5 commit 33bae1a

File tree

4 files changed

+20
-2
lines changed

4 files changed

+20
-2
lines changed

CHANGES

+2
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ Relase date to be decided, codename to be chosen.
6666
flashing on sessions implementations which use external storage.
6767
- Changed the behavior of tuple return values from functions. They are no
6868
longer arguments to the response object, they now have a defined meaning.
69+
- Added :attr:`flask.Flask.request_globals_class` to allow a specific class to
70+
be used on creation of the :data:`~flask.g` instance of each request.
6971

7072
Version 0.8.1
7173
-------------

flask/app.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
find_package
2929
from .wrappers import Request, Response
3030
from .config import ConfigAttribute, Config
31-
from .ctx import RequestContext, AppContext
31+
from .ctx import RequestContext, AppContext, _RequestGlobals
3232
from .globals import _request_ctx_stack, request
3333
from .sessions import SecureCookieSessionInterface
3434
from .module import blueprint_is_module
@@ -148,6 +148,11 @@ class Flask(_PackageBoundObject):
148148
#: :class:`~flask.Response` for more information.
149149
response_class = Response
150150

151+
#: The class that is used for the :data:`~flask.g` instance.
152+
#:
153+
#: .. versionadded:: 0.9
154+
request_globals_class = _RequestGlobals
155+
151156
#: The debug flag. Set this to `True` to enable debugging of the
152157
#: application. In debug mode the debugger will kick in when an unhandled
153158
#: exception ocurrs and the integrated server will automatically reload

flask/ctx.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919

2020
class _RequestGlobals(object):
21+
"""A plain object."""
2122
pass
2223

2324

@@ -139,7 +140,7 @@ def __init__(self, app, environ):
139140
self.app = app
140141
self.request = app.request_class(environ)
141142
self.url_adapter = app.create_url_adapter(self.request)
142-
self.g = _RequestGlobals()
143+
self.g = app.request_globals_class()
143144
self.flashes = None
144145
self.session = None
145146

flask/testsuite/appctx.py

+10
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,16 @@ def cleanup(exception):
6565

6666
self.assert_equal(cleanup_stuff, [None])
6767

68+
def test_custom_request_globals_class(self):
69+
class CustomRequestGlobals(object):
70+
def __init__(self):
71+
self.spam = 'eggs'
72+
app = flask.Flask(__name__)
73+
app.request_globals_class = CustomRequestGlobals
74+
with app.test_request_context():
75+
self.assert_equal(
76+
flask.render_template_string('{{ g.spam }}'), 'eggs')
77+
6878

6979
def suite():
7080
suite = unittest.TestSuite()

0 commit comments

Comments
 (0)