Skip to content

Commit

Permalink
Change flask KonfigProxy to behave like flask config
Browse files Browse the repository at this point in the history
  • Loading branch information
Samuel Martin Cantalejo authored and Stranger6667 committed Jan 10, 2020
1 parent 2697aaa commit 4ce5c2d
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 12 deletions.
3 changes: 3 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ Changelog
`Unreleased`_
-------------

Fixed
~~~~~
- Change Flask KonfigProxy to behave like Flask config.

`0.7.2`_ - 2019-07-18
---------------------
Expand Down
24 changes: 12 additions & 12 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -585,18 +585,18 @@ Flask extension
There is an extension for ``Flask`` that replaces ``Flask.config`` with ``Konfig`` instance and adds
all ``konfetti`` features to your ``app.config``.
```python
from flask import Flask
from konfetti.contrib.flask import FlaskKonfig
from .settings import config
.. code:: python
from flask import Flask
from konfetti.contrib.flask import FlaskKonfig
from .settings import config
app = Flask(__name__)
FlaskKonfig(app, config, CUSTOM_OPTION=42)
app = Flask(__name__)
FlaskKonfig(app, config, CUSTOM_OPTION=42)
...
...
# Taken from Vault
assert app.config.SECRET == "value"
# Manually specified
assert app.config.CUSTOM_OPTION == 42
```
# Taken from Vault
assert app.config.SECRET == "value"
# Manually specified
assert app.config.CUSTOM_OPTION == 42
12 changes: 12 additions & 0 deletions src/konfetti/contrib/flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ class KonfigProxy(object):
flask_config = attr.ib()
konfig = attr.ib()

def get(self, key, default=None):
try:
return self._get(key)
except KeyError:
return default

def _get(self, key):
try:
return self.kwargs[key]
Expand All @@ -40,6 +46,12 @@ def _get(self, key):
def __getitem__(self, item):
return self._get(item)

def __setitem__(self, key, value):
self.flask_config[key] = value

def __contains__(self, item):
return self.get(item) is not None

def __getattr__(self, item):
try:
return getattr(self.flask_config, item)
Expand Down
9 changes: 9 additions & 0 deletions test/test_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,12 @@ def assert_config(config):
# Overridden via explicit kwarg
assert config.SERVER_NAME == "test"
assert config["SERVER_NAME"] == "test"
# Settings flask config item via __setitem__
config["CONF_KEY"] = "conf_item"
assert config["CONF_KEY"] == "conf_item"
# Testing __contains__
assert "KEY" in config
assert "NOT_EXISTING_KEY" not in config
# Testing get method
assert config.get("KEY") == "value"
assert config.get("NOT_EXISTING_KEY") is None

0 comments on commit 4ce5c2d

Please sign in to comment.