Skip to content

Commit

Permalink
Merge pull request #1509 from ThiefMaster/appctxglobals-candy
Browse files Browse the repository at this point in the history
Add pop and setdefault to AppCtxGlobals
  • Loading branch information
untitaker committed Jun 30, 2015
2 parents 595fb7e + bbaf20d commit 3747487
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ Version 1.0
- Don't leak exception info of already catched exceptions to context teardown
handlers (pull request ``#1393``).
- Allow custom Jinja environment subclasses (pull request ``#1422``).
- ``flask.g`` now has ``pop()`` and ``setdefault`` methods.

Version 0.10.2
--------------
Expand Down
3 changes: 3 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ thing, like it does for :class:`request` and :class:`session`.
It's now also possible to use the ``in`` operator on it to see if an
attribute is defined and it yields all keys on iteration.

As of 1.0 you can use :meth:`pop` and :meth:`setdefault` in the same
way you would use them on a dictionary.

This is a proxy. See :ref:`notes-on-proxies` for more information.


Expand Down
9 changes: 9 additions & 0 deletions flask/ctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ class _AppCtxGlobals(object):
def get(self, name, default=None):
return self.__dict__.get(name, default)

def pop(self, name, default=_sentinel):
if default is _sentinel:
return self.__dict__.pop(name)
else:
return self.__dict__.pop(name, default)

def setdefault(self, name, default=None):
self.__dict__.setdefault(name, default)

def __contains__(self, item):
return item in self.__dict__

Expand Down
22 changes: 22 additions & 0 deletions tests/test_appctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,28 @@ def cleanup(exception):

assert cleanup_stuff == [None]

def test_app_ctx_globals_methods():
app = flask.Flask(__name__)
with app.app_context():
# get
assert flask.g.get('foo') is None
assert flask.g.get('foo', 'bar') == 'bar'
# __contains__
assert 'foo' not in flask.g
flask.g.foo = 'bar'
assert 'foo' in flask.g
# setdefault
flask.g.setdefault('bar', 'the cake is a lie')
flask.g.setdefault('bar', 'hello world')
assert flask.g.bar == 'the cake is a lie'
# pop
assert flask.g.pop('bar') == 'the cake is a lie'
with pytest.raises(KeyError):
flask.g.pop('bar')
assert flask.g.pop('bar', 'more cake') == 'more cake'
# __iter__
assert list(flask.g) == ['foo']

def test_custom_app_ctx_globals_class():
class CustomRequestGlobals(object):
def __init__(self):
Expand Down

0 comments on commit 3747487

Please sign in to comment.