Skip to content

Commit

Permalink
reformat all with black
Browse files Browse the repository at this point in the history
  • Loading branch information
tomcounsell committed Jul 20, 2022
1 parent 4f65d89 commit 0b322ae
Show file tree
Hide file tree
Showing 75 changed files with 1,650 additions and 906 deletions.
2 changes: 1 addition & 1 deletion src/popoto/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

class ModelException(Exception):
pass


class FinanceException(Exception):
pass
27 changes: 18 additions & 9 deletions src/popoto/fields/auto_field_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

import redis

logger = logging.getLogger('POPOTO.field')
logger = logging.getLogger("POPOTO.field")


class AutoFieldMixin:
"""
Expand All @@ -14,6 +15,7 @@ class AutoFieldMixin:
They auto-generated key is random and newly generated for a model instance.
Model instances with otherwise identical properties are saved as separate instances with different auto-keys.
"""

# todo: add support for https://github.com/ai/nanoid

auto: bool = True
Expand All @@ -23,9 +25,9 @@ class AutoFieldMixin:
def __init__(self, **kwargs):
super().__init__(**kwargs)
autokeyfield_defaults = {
'auto': True,
'auto_uuid_length': 32,
'auto_id': "",
"auto": True,
"auto_uuid_length": 32,
"auto_id": "",
}
self.field_defaults.update(autokeyfield_defaults)
# set field options, let kwargs override
Expand All @@ -35,19 +37,26 @@ def __init__(self, **kwargs):
@classmethod
def is_valid(cls, field, value, null_check=True, **kwargs) -> bool:
if value and len(value) != field.auto_uuid_length:
logger.error(f"auto key value is length {len(value)}. It should be {field.auto_uuid_length}")
logger.error(
f"auto key value is length {len(value)}. It should be {field.auto_uuid_length}"
)
return False
return super().is_valid(field, value, null_check=null_check, **kwargs)

def get_new_auto_key_value(self):
return uuid.uuid4().hex[:self.auto_uuid_length]
return uuid.uuid4().hex[: self.auto_uuid_length]

def set_auto_key_value(self, force: bool = False):
if self.auto or force:
self.default = self.get_new_auto_key_value()

@classmethod
def on_save(cls, model_instance: 'Model', field_name: str, field_value, pipeline: redis.client.Pipeline = None, **kwargs):
def on_save(
cls,
model_instance: "Model",
field_name: str,
field_value,
pipeline: redis.client.Pipeline = None,
**kwargs,
):
return pipeline if pipeline else None


67 changes: 48 additions & 19 deletions src/popoto/fields/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,22 @@

from ..models.db_key import DB_key

logger = logging.getLogger('POPOTO.field')
logger = logging.getLogger("POPOTO.field")

VALID_FIELD_TYPES = {
int, float, Decimal, str, bool, bytes, list, dict, set, tuple, date, datetime, time,
int,
float,
Decimal,
str,
bool,
bytes,
list,
dict,
set,
tuple,
date,
datetime,
time,
}


Expand Down Expand Up @@ -42,15 +54,15 @@ class Field(metaclass=FieldBase):

def __init__(self, **kwargs):
self.field_defaults = { # default
'type': str,
'key': False,
'unique': False,
'auto': False,
'null': True,
'value': None,
'max_length': 1024, # Redis limit is 512MB
'default': None,
'sorted': False,
"type": str,
"key": False,
"unique": False,
"auto": False,
"null": True,
"value": None,
"max_length": 1024, # Redis limit is 512MB
"default": None,
"sorted": False,
}
# set field_options, let kwargs override
field_options = self.field_defaults.copy()
Expand All @@ -69,7 +81,9 @@ def is_valid(cls, field, value, null_check=True, **kwargs) -> bool:
logger.error(f"field {field} is null")
return False
elif not isinstance(value, field.type):
logger.error(f"field {field} is type {field.type}. But value is {type(value)}")
logger.error(
f"field {field} is type {field.type}. But value is {type(value)}"
)
return False
if field.type == str and len(str(value)) > field.max_length:
logger.error(f"{field} value is greater than max_length={field.max_length}")
Expand All @@ -85,17 +99,22 @@ def format_value_pre_save(self, field_value):
return field_value

@classmethod
def get_special_use_field_db_key(cls, model: 'Model', *field_names) -> DB_key:
def get_special_use_field_db_key(cls, model: "Model", *field_names) -> DB_key:
"""
For use by child class when implementing additional Redis data structures
Children implementing more than one new structure will need to augment this.
"""
return DB_key(cls.field_class_key, model._meta.db_class_key, *field_names)


@classmethod
def on_save(cls, model_instance: 'Model', field_name: str, field_value, pipeline: redis.client.Pipeline = None,
**kwargs):
def on_save(
cls,
model_instance: "Model",
field_name: str,
field_value,
pipeline: redis.client.Pipeline = None,
**kwargs,
):
"""
for parent classes to override.
will run for every field of the model instance, including null attributes
Expand All @@ -114,7 +133,14 @@ def on_save(cls, model_instance: 'Model', field_name: str, field_value, pipeline
return pipeline if pipeline else None

@classmethod
def on_delete(cls, model_instance: 'Model', field_name: str, field_value, pipeline=None, **kwargs):
def on_delete(
cls,
model_instance: "Model",
field_name: str,
field_value,
pipeline=None,
**kwargs,
):
"""
for parent classes to override.
will run for every field of the model instance, including null attributes
Expand All @@ -130,12 +156,15 @@ def get_filter_query_params(self, field_name: str) -> set:
return set()

@classmethod
def filter_query(cls, model: 'Model', field_name: str, **query_params) -> set:
def filter_query(cls, model: "Model", field_name: str, **query_params) -> set:
"""
:param model: the popoto.Model to query from
:param field_name: the name of the field being filtered on
:param query_params: dict of filter args and values
:return: set{db_key, db_key, ..}
"""
from ..models.query import QueryException
raise QueryException("Query filter not allowed on base Field. Consider using a KeyField")

raise QueryException(
"Query filter not allowed on base Field. Consider using a KeyField"
)

0 comments on commit 0b322ae

Please sign in to comment.