Skip to content

Commit

Permalink
Run black
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeengland committed Jan 26, 2020
1 parent eb85b4f commit f4128db
Show file tree
Hide file tree
Showing 15 changed files with 74 additions and 89 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pythonpackage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ jobs:
env:
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
- name: Run Black code formatter check
run: black --check
run: black --check .
35 changes: 8 additions & 27 deletions example/example/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,8 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'tasks',
'setty'
'setty',
]

MIDDLEWARE = [
Expand Down Expand Up @@ -82,37 +81,19 @@
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3')}}

CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211'}}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]


Expand All @@ -135,6 +116,6 @@

STATIC_URL = '/static/'

#SETTY_BACKEND = 'DatabaseBackend'
# SETTY_BACKEND = 'DatabaseBackend'
SETTY_BACKEND = 'CacheBackend'
SETTY_NOT_FOUND_VALUE = '__notfound__'
4 changes: 2 additions & 2 deletions example/tasks/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]
dependencies = []

operations = [
migrations.CreateModel(
Expand Down
1 change: 1 addition & 0 deletions setty/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
class LazyConfig(LazyObject):
def _setup(self):
from .wrapper import Settings

self._wrapped = Settings()


Expand Down
8 changes: 4 additions & 4 deletions setty/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,16 @@


class SettingsForm(forms.ModelForm):

def __init__(self, *args, instance=None, **kwargs):
# Loading the stringified value does not work without manually passing this in as initial data.
# This is due to it being a model property. We can safely ignore the provided inital kwarg as it is merged later
kwargs.pop('initial', None)
initial_data = {'value_unpacked': getattr(instance, 'value_unpacked', None)}
super().__init__(*args, initial=initial_data, instance=instance, **kwargs)

value_unpacked = forms.CharField(label='Value',
help_text='The value to store. '
'List and Dict data types should be defined as JSON strings.')
value_unpacked = forms.CharField(
label='Value', help_text='The value to store. ' 'List and Dict data types should be defined as JSON strings.'
)

def clean_value_unpacked(self):
serializer = SERIALIZERS[self.cleaned_data['type']]
Expand All @@ -49,6 +48,7 @@ def save(self, commit=True):
# Reset item in cache if changed in the admin
if settings.SETTY_BACKEND == 'CacheBackend':
from setty.backend import CacheBackend

CacheBackend().set_in_cache(instance.name, instance.value)

return instance
Expand Down
7 changes: 5 additions & 2 deletions setty/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class DatabaseBackend:
"""
The simple DatabaseBackend is backed by the Django model storing these settings
"""

def get_all(self, app_name=None):
if app_name:
return SettySettings.objects.filter(app_name=app_name).all()
Expand All @@ -29,8 +30,9 @@ def get(self, name):
def set(self, name, value):
updated_count = SettySettings.objects.filter(name=name).update(value=value)
if not updated_count:
raise SettingDoesNotExistError(f'Error setting value for {name} - '
f'this setting does not exist in the database!')
raise SettingDoesNotExistError(
f'Error setting value for {name} - ' f'this setting does not exist in the database!'
)
return value


Expand All @@ -39,6 +41,7 @@ class CacheBackend(DatabaseBackend):
CacheBackend uses the Django cache setup to cache values instead of accessing the
database on each get call.
"""

def get(self, name):
cache_key = self._make_cache_key(name)
setting_value = cache.get(cache_key, '__expired__')
Expand Down
25 changes: 17 additions & 8 deletions setty/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
# Generated by Django 2.0.3 on 2018-10-25 18:51

from django.db import migrations, models
import picklefield.fields
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]
dependencies = []

operations = [
migrations.CreateModel(
name='SettySettings',
fields=[
('name', models.CharField(max_length=190, primary_key=True, serialize=False)),
('value', picklefield.fields.PickledObjectField(editable=False)),
('type', models.CharField(choices=[('bool', 'Bool'), ('dict', 'Dict'), ('float', 'Float'), ('integer', 'Integer'), ('list', 'List'), ('string', 'String')], max_length=8)),
(
'type',
models.CharField(
choices=[
('bool', 'Bool'),
('dict', 'Dict'),
('float', 'Float'),
('integer', 'Integer'),
('list', 'List'),
('string', 'String'),
],
max_length=8,
),
),
('created_time', models.DateTimeField(auto_now_add=True)),
('updated_time', models.DateTimeField(auto_now=True)),
],
options={
'verbose_name': 'Setty Settings',
'verbose_name_plural': 'Setty Settings',
},
options={'verbose_name': 'Setty Settings', 'verbose_name_plural': 'Setty Settings', },
),
]
14 changes: 13 additions & 1 deletion setty/migrations/0002_settysettings_app_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='settysettings',
name='app_name',
field=models.CharField(blank=True, choices=[('django.contrib.admin', 'django.contrib.admin'), ('django.contrib.auth', 'django.contrib.auth'), ('django.contrib.contenttypes', 'django.contrib.contenttypes'), ('django.contrib.sessions', 'django.contrib.sessions'), ('django.contrib.messages', 'django.contrib.messages'), ('django.contrib.staticfiles', 'django.contrib.staticfiles'), ('setty.apps.DjangoSettyConfig', 'setty.apps.DjangoSettyConfig')], max_length=190),
field=models.CharField(
blank=True,
choices=[
('django.contrib.admin', 'django.contrib.admin'),
('django.contrib.auth', 'django.contrib.auth'),
('django.contrib.contenttypes', 'django.contrib.contenttypes'),
('django.contrib.sessions', 'django.contrib.sessions'),
('django.contrib.messages', 'django.contrib.messages'),
('django.contrib.staticfiles', 'django.contrib.staticfiles'),
('setty.apps.DjangoSettyConfig', 'setty.apps.DjangoSettyConfig'),
],
max_length=190,
),
),
]
5 changes: 3 additions & 2 deletions setty/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.db import models
from django.conf import settings
from django.db import models
from picklefield import PickledObjectField


Expand All @@ -20,7 +20,8 @@ class TypeChoices:
(STRING, 'String'),
)

APP_CHOICES = [ (app,app) for app in settings.INSTALLED_APPS ]

APP_CHOICES = [(app, app) for app in settings.INSTALLED_APPS]


class SettySettings(models.Model):
Expand Down
25 changes: 5 additions & 20 deletions setty/tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,7 @@
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}


# Application definition
Expand All @@ -47,7 +41,6 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'setty.apps.DjangoSettyConfig',
]

Expand Down Expand Up @@ -85,18 +78,10 @@
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },
]

# Internationalization
Expand Down
1 change: 0 additions & 1 deletion setty/tests/test_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

@override_settings(SETTY_BACKEND='DatabaseBackend')
class AdminSettingsFormTests(TestCase):

def _validate_invalid_form(self, data_type):
form = SettingsForm(data={'name': 'mysetting', 'type': data_type, 'value_unpacked': 'invalid'})
self.assertFalse(form.is_valid())
Expand Down
26 changes: 14 additions & 12 deletions setty/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ def setUpTestData(cls):

@override_settings(SETTY_BACKEND='DatabaseBackend')
class DatabaseBackendTests(BaseBackendTestsMixin, TestCase):

@classmethod
def setUpTestData(cls):
super().setUpTestData()
Expand Down Expand Up @@ -58,8 +57,10 @@ def test_get_returns_dict(self):
self.assertEqual(self.backend.get('mydict'), {'a': 1, 'b': 2})

def test_set_invalid_setting_raises_exception(self):
with self.assertRaisesMessage(SettingDoesNotExistError, f'Error setting value for invalid - '
f'this setting does not exist in the database!'):
with self.assertRaisesMessage(
SettingDoesNotExistError,
f'Error setting value for invalid - ' f'this setting does not exist in the database!',
):
self.backend.set('invalid', True)

def test_set_updates_bool(self):
Expand Down Expand Up @@ -90,21 +91,22 @@ def test_set_updates_dict(self):
@override_settings(SETTY_BACKEND='CacheBackend', SETTY_CACHE_PREFIX='_mock_key_')
@patch('setty.backend.cache')
class CacheBackendTest(BaseBackendTestsMixin, TestCase):

def setUp(self):
self.backend = CacheBackend()

def test_load_all_settings_into_cache_calls_set_for_all_settings(self, mock_cache):
self.backend.load_all_settings_into_cache()

mock_cache.set.assert_has_calls([
call('_mock_key_:mybool', True, 3600),
call('_mock_key_:mydict', {'a': 1, 'b': 2}, 3600),
call('_mock_key_:myfloat', 3.142, 3600),
call('_mock_key_:myinteger', 123, 3600),
call('_mock_key_:mylist', [1, 2, 3, 4], 3600),
call('_mock_key_:mystring', 'test_string', 3600),
])
mock_cache.set.assert_has_calls(
[
call('_mock_key_:mybool', True, 3600),
call('_mock_key_:mydict', {'a': 1, 'b': 2}, 3600),
call('_mock_key_:myfloat', 3.142, 3600),
call('_mock_key_:myinteger', 123, 3600),
call('_mock_key_:mylist', [1, 2, 3, 4], 3600),
call('_mock_key_:mystring', 'test_string', 3600),
]
)

@override_settings(SETTY_CACHE_TTL=5)
def test_set_method(self, mock_cache):
Expand Down
2 changes: 0 additions & 2 deletions setty/tests/test_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from unittest.mock import patch

from django.test import TestCase, override_settings

from setty.backend import DatabaseBackend, CacheBackend
from setty.exceptions import InvalidConfigurationError
from setty.models import SettySettings as SettySettingsModel
from setty.wrapper import Settings, _load_backend_class


class WrapperTests(TestCase):

@classmethod
def setUpTestData(cls):
super().setUpTestData()
Expand Down
1 change: 1 addition & 0 deletions setty/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class Settings:
"""
Wrapper class used for accessing/updating setty settings
"""

_backend = _load_backend_class()

def __getattr__(self, key):
Expand Down
7 changes: 0 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,16 @@

setup(
name='django-setty',

version='3.2.0',

author='Michael England',
author_email='[email protected]',

license='Apache License Version 2.0',

packages=['setty', 'setty.migrations'],
include_package_data=True,

url='https://github.com/mikeengland/django-setty',

description='Django app allowing users to configure settings dynamically in the Admin screen',
long_description=long_description,
long_description_content_type='text/markdown',

classifiers=[
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
Expand Down

0 comments on commit f4128db

Please sign in to comment.