aboutsummaryrefslogtreecommitdiff
path: root/server/szurubooru/func/util.py
diff options
context:
space:
mode:
Diffstat (limited to 'server/szurubooru/func/util.py')
-rw-r--r--server/szurubooru/func/util.py69
1 files changed, 38 insertions, 31 deletions
diff --git a/server/szurubooru/func/util.py b/server/szurubooru/func/util.py
index 4638d4b..eacdc2a 100644
--- a/server/szurubooru/func/util.py
+++ b/server/szurubooru/func/util.py
@@ -1,29 +1,32 @@
-import os
import hashlib
+import os
import re
import tempfile
-from typing import Any, Optional, Union, Tuple, List, Dict, Generator, TypeVar
-from datetime import datetime, timedelta
from contextlib import contextmanager
-from szurubooru import errors
+from datetime import datetime, timedelta
+from typing import Any, Dict, Generator, List, Optional, Tuple, TypeVar, Union
+from szurubooru import errors
-T = TypeVar('T')
+T = TypeVar("T")
def snake_case_to_lower_camel_case(text: str) -> str:
- components = text.split('_')
- return components[0].lower() + \
- ''.join(word[0].upper() + word[1:].lower() for word in components[1:])
+ components = text.split("_")
+ return components[0].lower() + "".join(
+ word[0].upper() + word[1:].lower() for word in components[1:]
+ )
def snake_case_to_upper_train_case(text: str) -> str:
- return '-'.join(
- word[0].upper() + word[1:].lower() for word in text.split('_'))
+ return "-".join(
+ word[0].upper() + word[1:].lower() for word in text.split("_")
+ )
def snake_case_to_lower_camel_case_keys(
- source: Dict[str, Any]) -> Dict[str, Any]:
+ source: Dict[str, Any]
+) -> Dict[str, Any]:
target = {}
for key, value in source.items():
target[snake_case_to_lower_camel_case(key)] = value
@@ -35,7 +38,7 @@ def create_temp_file(**kwargs: Any) -> Generator:
(descriptor, path) = tempfile.mkstemp(**kwargs)
os.close(descriptor)
try:
- with open(path, 'r+b') as handle:
+ with open(path, "r+b") as handle:
yield handle
finally:
os.remove(path)
@@ -65,7 +68,7 @@ def flatten_list(source: List[List[T]]) -> List[T]:
def get_md5(source: Union[str, bytes]) -> str:
if not isinstance(source, bytes):
- source = source.encode('utf-8')
+ source = source.encode("utf-8")
md5 = hashlib.md5()
md5.update(source)
return md5.hexdigest()
@@ -73,7 +76,7 @@ def get_md5(source: Union[str, bytes]) -> str:
def get_sha1(source: Union[str, bytes]) -> str:
if not isinstance(source, bytes):
- source = source.encode('utf-8')
+ source = source.encode("utf-8")
sha1 = hashlib.sha1()
sha1.update(source)
return sha1.hexdigest()
@@ -84,12 +87,13 @@ def flip(source: Dict[Any, Any]) -> Dict[Any, Any]:
def is_valid_email(email: Optional[str]) -> bool:
- ''' Return whether given email address is valid or empty. '''
- return not email or re.match(r'^[^@]*@[^@]*\.[^@]*$', email) is not None
+ """ Return whether given email address is valid or empty. """
+ return not email or re.match(r"^[^@]*@[^@]*\.[^@]*$", email) is not None
+
+class dotdict(dict):
+ """ dot.notation access to dictionary attributes. """
-class dotdict(dict): # pylint: disable=invalid-name
- ''' dot.notation access to dictionary attributes. '''
def __getattr__(self, attr: str) -> Any:
return self.get(attr)
@@ -98,51 +102,54 @@ class dotdict(dict): # pylint: disable=invalid-name
def parse_time_range(value: str) -> Tuple[datetime, datetime]:
- ''' Return tuple containing min/max time for given text representation. '''
+ """ Return tuple containing min/max time for given text representation. """
one_day = timedelta(days=1)
one_second = timedelta(seconds=1)
almost_one_day = one_day - one_second
value = value.lower()
if not value:
- raise errors.ValidationError('Empty date format.')
+ raise errors.ValidationError("Empty date format.")
- if value == 'today':
+ if value == "today":
now = datetime.utcnow()
return (
datetime(now.year, now.month, now.day, 0, 0, 0),
- datetime(now.year, now.month, now.day, 0, 0, 0) + almost_one_day
+ datetime(now.year, now.month, now.day, 0, 0, 0) + almost_one_day,
)
- if value == 'yesterday':
+ if value == "yesterday":
now = datetime.utcnow()
return (
datetime(now.year, now.month, now.day, 0, 0, 0) - one_day,
- datetime(now.year, now.month, now.day, 0, 0, 0) - one_second)
+ datetime(now.year, now.month, now.day, 0, 0, 0) - one_second,
+ )
- match = re.match(r'^(\d{4})$', value)
+ match = re.match(r"^(\d{4})$", value)
if match:
year = int(match.group(1))
return (datetime(year, 1, 1), datetime(year + 1, 1, 1) - one_second)
- match = re.match(r'^(\d{4})-(\d{1,2})$', value)
+ match = re.match(r"^(\d{4})-(\d{1,2})$", value)
if match:
year = int(match.group(1))
month = int(match.group(2))
return (
datetime(year, month, 1),
- datetime(year, month + 1, 1) - one_second)
+ datetime(year, month + 1, 1) - one_second,
+ )
- match = re.match(r'^(\d{4})-(\d{1,2})-(\d{1,2})$', value)
+ match = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", value)
if match:
year = int(match.group(1))
month = int(match.group(2))
day = int(match.group(3))
return (
datetime(year, month, day),
- datetime(year, month, day + 1) - one_second)
+ datetime(year, month, day + 1) - one_second,
+ )
- raise errors.ValidationError('Invalid date format: %r.' % value)
+ raise errors.ValidationError("Invalid date format: %r." % value)
def icase_unique(source: List[str]) -> List[str]:
@@ -172,4 +179,4 @@ def get_column_size(column: Any) -> Optional[int]:
def chunks(source_list: List[Any], part_size: int) -> Generator:
for i in range(0, len(source_list), part_size):
- yield source_list[i:i + part_size]
+ yield source_list[i : i + part_size]

© 2015 - 2026 Jakob L. Kreuze