Skip to content

Commit

Permalink
Merge pull request #78 from RadarJam/Recursive-assignment-of-fields-i…
Browse files Browse the repository at this point in the history
…n-settings.py-to-the-app.settings-object

Recursive assignment of fields in settings.py to the app.settings object
  • Loading branch information
dotchetter authored Sep 25, 2023
2 parents 32aa663 + 3056976 commit 39d658e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
24 changes: 21 additions & 3 deletions pyttman/core/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
import json
from collections import UserDict


import pyttman
from pyttman.core.containers import MessageMixin, Reply
Expand Down Expand Up @@ -32,7 +35,6 @@ def depr_graceful(message: str, version: str):
out = f"{message} - This was deprecated in version {version}."
warnings.warn(out, DeprecationWarning)


class Settings:
"""
Dataclass holding settings configured in the settings.py
Expand All @@ -48,7 +50,10 @@ class Settings:
aren't valid settings.
"""

def __init__(self, **kwargs):
def __init__(self, dictionary=None, **kwargs):
if dictionary is None:
dictionary = {}
self.__dict__.update(dictionary)
self.APPEND_LOG_FILES: bool = True
self.MIDDLEWARE: dict | None = None
self.ABILITIES: list | None = None
Expand All @@ -60,14 +65,27 @@ def __init__(self, **kwargs):
self.LOG_FORMAT: str | None = None
self.LOG_TO_STDOUT: bool = False

[setattr(self, k, v) for k, v in kwargs.items()
[self._set_attr(k, v) for k, v in kwargs.items()
if not inspect.ismodule(v)
and not inspect.isfunction(v)]

def __getitem__(self, item):
return self.__dict__[item]

def _set_attr(self, k, v):
tmp = v
if isinstance(v, dict):
tmp = Settings._dict_to_object(v)

setattr(self, k, tmp)

def __repr__(self):
_attrs = {name: value for name, value in self.__dict__.items()}
return f"Settings({_attrs})"

@staticmethod
def _dict_to_object(dictionary):
return json.loads(json.dumps(dictionary), object_hook=Settings)

def _generate_name(name):
"""
Expand Down
32 changes: 32 additions & 0 deletions tests/core/test_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from tests.module_helper import PyttmanInternalBaseTestCase
from pyttman.core.internals import Settings

from importlib import import_module
import pytest

@pytest.fixture
def mockSettings():

mock_settings = {
"d":{
"k1":"v1",
"k2":{
"a":"a",
"b":"b"
}
},
"foo":"bar"
}

return Settings(**mock_settings)

def test_read_settings_with_dictionary(mockSettings):
assert mockSettings.d.k2.a == "a"
assert mockSettings.d["k2"].a == "a"
assert mockSettings.d["k2"]["a"] == "a"

assert mockSettings.d.k1 == "v1"
assert mockSettings.d["k1"] == "v1"

assert mockSettings.foo == "bar"

0 comments on commit 39d658e

Please sign in to comment.