Skip to content

Commit

Permalink
moving to using the subscriptable types in the standards collection r…
Browse files Browse the repository at this point in the history
…ather than unnecessary imports from typing
  • Loading branch information
Max-Derner committed Mar 27, 2024
1 parent 77925d5 commit b8fa76d
Show file tree
Hide file tree
Showing 16 changed files with 46 additions and 58 deletions.
11 changes: 5 additions & 6 deletions app/local_use/basic_queries.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from typing import Dict, List
from datetime import datetime

from app.support.common.logger import get_full_logger
Expand All @@ -14,15 +13,15 @@
logger = get_full_logger()


def user_driven_get_all_of_pets_records() -> List[Dict]:
def user_driven_get_all_of_pets_records() -> list[dict]:
logger.info("Please enter the name of the pet whose records you wish to see:")
pet_name = input()
logger.info(f"You entered '{pet_name}'")
records = get_all_of_pets_records(pet_name=pet_name)
return records


def user_driven_get_all_of_pets_record_type() -> List[Dict]:
def user_driven_get_all_of_pets_record_type() -> list[dict]:
logger.info("Please enter the name of the pet whose records you wish to see:")
pet_name = input()
logger.info(f"You entered '{pet_name}'")
Expand All @@ -40,7 +39,7 @@ def user_driven_get_all_of_pets_record_type() -> List[Dict]:
return records


def upcoming_records_after_point_in_time(point_in_time: datetime) -> List[Dict]:
def upcoming_records_after_point_in_time(point_in_time: datetime) -> list[dict]:
records = []
records.extend(
get_all_records_of_appointment_in_timeframe(
Expand All @@ -57,13 +56,13 @@ def upcoming_records_after_point_in_time(point_in_time: datetime) -> List[Dict]:
return records


def upcoming_records() -> List[Dict]:
def upcoming_records() -> list[dict]:
return upcoming_records_after_point_in_time(
point_in_time=datetime.now()
)


def user_driven_upcoming_records_after_point_in_time() -> List[Dict]:
def user_driven_upcoming_records_after_point_in_time() -> list[dict]:
logger.info("Please enter a year: ")
year = int(input())
logger.info("Please enter a month: ")
Expand Down
9 changes: 4 additions & 5 deletions app/support/common/logger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
import os
from typing import List
from .misc import ensure_directories_present


Expand Down Expand Up @@ -48,7 +47,7 @@
_CONSOLE_LOG_LEVEL = logging.INFO
_DEBUG_FILE_LOG_LEVEL = logging.DEBUG

handlers: List[logging.Handler]
handlers: list[logging.Handler]

config_message = 'logger configured:\n'
config_message += 'logging will go to 2 output files\n'
Expand Down Expand Up @@ -97,7 +96,7 @@ def _get_file_handler(
def _get_handlers(create_console_stream_handler: bool = True,
create_console_file_handler: bool = True,
create_debug_file_handler: bool = True
) -> List[None | logging.Handler]:
) -> list[None | logging.Handler]:
console_stream_handler, console_file_handler, debug_file_handler = None, None, None
if create_console_stream_handler or create_console_file_handler:
console_output_formatter = _get_console_output_formatter()
Expand Down Expand Up @@ -126,7 +125,7 @@ def _get_handlers(create_console_stream_handler: bool = True,


def _add_handlers(
handlers: None | List[logging.FileHandler] | List[logging.StreamHandler],
handlers: None | list[logging.FileHandler] | list[logging.StreamHandler],
logger: logging.Logger
):
for handler in handlers:
Expand All @@ -152,7 +151,7 @@ def _set_up_logger(logger: logging.Logger,
logger.info(config_message)


def get_output_directories() -> List[str]:
def get_output_directories() -> list[str]:
return_list = []
output_files = [
_RELATIVE_CONSOLE_OUTPUT_FILE_PATH,
Expand Down
3 changes: 1 addition & 2 deletions app/support/common/misc.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from datetime import datetime, timezone
import os
from typing import List
from json import JSONEncoder
from decimal import Decimal


def ensure_directories_present(directories: List[str]):
def ensure_directories_present(directories: list[str]):
for directory in directories:
ensure_directory_present(dir=directory)

Expand Down
10 changes: 5 additions & 5 deletions app/support/data_access_layer/get_records.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from datetime import datetime, timezone
from decimal import Decimal
from typing import List, Dict, Optional
from typing import Optional

from boto3.dynamodb.conditions import Key, Attr

from support.common.aws_resources import get_pet_table_resource
from support.data_access_layer.records.pet_table_models import RecordType


def _arbitrary_pet_table_query(**kwargs) -> List[Dict]:
def _arbitrary_pet_table_query(**kwargs) -> list[dict]:
"""
This function handles everything around DynamoDB queries,
all you have to do is supply the args and kwargs for a query.
Expand All @@ -27,7 +27,7 @@ def _arbitrary_pet_table_query(**kwargs) -> List[Dict]:
return items


def get_all_of_pets_records(pet_name: str) -> List[Dict]:
def get_all_of_pets_records(pet_name: str) -> list[dict]:
query_params = {
'KeyConditionExpression': Key('name').eq(pet_name),
}
Expand All @@ -37,7 +37,7 @@ def get_all_of_pets_records(pet_name: str) -> List[Dict]:
def get_all_of_pets_record_type(
pet_name: str,
record_type: RecordType
) -> List[Dict]:
) -> list[dict]:
query_params = {
'KeyConditionExpression': Key('name').eq(pet_name) & Key('sort_key').begins_with(record_type.value)
}
Expand All @@ -48,7 +48,7 @@ def get_all_of_pets_record_type_after_point_in_time(
pet_name: str,
point_in_time: datetime,
record_type: RecordType
) -> List[Dict]:
) -> list[dict]:
query_params = {
'KeyConditionExpression': Key('name').eq(pet_name) & Key('sort_key').begins_with(record_type.value),
'FilterExpression': Attr('date_time').gt(Decimal(point_in_time.astimezone(tz=timezone.utc).timestamp()))
Expand Down
4 changes: 2 additions & 2 deletions app/support/data_access_layer/put_records.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import Dict, Optional
from typing import Optional

from support.common.logger import get_full_logger
from support.common.aws_resources import get_pet_table_resource
Expand Down Expand Up @@ -112,7 +112,7 @@ def put_observation_record(pet_name: str,


def _validate_record_then_put_in_pet_table(factory: AbstractRecordFactory,
record: Dict):
record: dict):
logger.info("Validating record")
if not factory.validate_record(record=record):
record = factory.coerce_record_to_valid_state(record=record)
Expand Down
8 changes: 3 additions & 5 deletions app/support/data_access_layer/records/abstract_record.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Dict

from pydantic import ValidationError, BaseModel

from app.support.common.logger import get_full_logger
Expand All @@ -16,10 +14,10 @@ def __init__(self):
# Models can be found in the pet_table_models.py file
raise NotImplementedError()

def produce_record(self) -> Dict:
def produce_record(self) -> dict:
raise NotImplementedError()

def validate_record(self, record: Dict) -> bool:
def validate_record(self, record: dict) -> bool:
logger.info(f"Received request to validate the record: {record}")
try:
self.model.model_validate(
Expand All @@ -33,7 +31,7 @@ def validate_record(self, record: Dict) -> bool:
logger.warning(str(e))
return False

def coerce_record_to_valid_state(self, record: Dict) -> None | Dict:
def coerce_record_to_valid_state(self, record: dict) -> None | dict:
"""Returns None if record cannot be coerced into valid state,
else returns newly valid record"""
logger.info(f"Received request to coerce record: {record}")
Expand Down
3 changes: 1 addition & 2 deletions app/support/data_access_layer/records/appointment_record.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from datetime import datetime, timezone
from typing import Dict
from decimal import Decimal

from app.support.data_access_layer.records.abstract_record import AbstractRecordFactory
Expand All @@ -21,7 +20,7 @@ def produce_record(
pet_name: str,
appointment_time: datetime,
description: str
) -> Dict[str, str | Decimal]:
) -> dict[str, str | Decimal]:
sort_key = f"{RecordType.APPOINTMENT.value}#{utc_timestamp_now()}"
illness_record = {
"name": pet_name,
Expand Down
3 changes: 1 addition & 2 deletions app/support/data_access_layer/records/details_record.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from typing import Dict
from datetime import datetime
from decimal import Decimal

Expand All @@ -24,7 +23,7 @@ def produce_record(
gender: str,
breed: str,
microchip_number: int
) -> Dict[str, str | Decimal]:
) -> dict[str, str | Decimal]:
details_record = {
"name": pet_name,
"sort_key": RecordType.DETAILS.value,
Expand Down
3 changes: 1 addition & 2 deletions app/support/data_access_layer/records/illness_record.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from datetime import datetime, timezone
from typing import Dict
from decimal import Decimal

from app.support.data_access_layer.records.abstract_record import AbstractRecordFactory
Expand All @@ -22,7 +21,7 @@ def produce_record(
ailment: str,
observed_time: datetime,
description: str
) -> Dict[str, str | Decimal]:
) -> dict[str, str | Decimal]:
sort_key = f"{RecordType.ILLNESS.value}#{ailment}#{utc_timestamp_now()}"
illness_record = {
"name": pet_name,
Expand Down
4 changes: 2 additions & 2 deletions app/support/data_access_layer/records/medication_record.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, Optional
from typing import Optional
from datetime import datetime, timezone
from decimal import Decimal

Expand All @@ -23,7 +23,7 @@ def produce_record(
name_of_medicine: str,
type_of_medicine: str,
next_due: Optional[datetime]
) -> Dict[str, str | Decimal | bool]:
) -> dict[str, str | Decimal | bool]:
sort_key = f"{RecordType.MEDICATION.value}#{type_of_medicine}#{utc_timestamp_now()}"
if next_due is None:
next_due_section = {
Expand Down
3 changes: 1 addition & 2 deletions app/support/data_access_layer/records/observation_record.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from datetime import datetime, timezone
from typing import Dict
from decimal import Decimal

from app.support.data_access_layer.records.abstract_record import AbstractRecordFactory
Expand All @@ -21,7 +20,7 @@ def produce_record(
pet_name: str,
observed_time: datetime,
description: str
) -> Dict[str, str | Decimal]:
) -> dict[str, str | Decimal]:
sort_key = f"{RecordType.OBSERVATION.value}#{utc_timestamp_now()}"
illness_record = {
"name": pet_name,
Expand Down
4 changes: 1 addition & 3 deletions app/support/find_reminders.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@

from datetime import timedelta

from typing import List, Dict

from support.common.misc import utc_datetime_now
from support.data_access_layer.get_records import (
get_all_records_of_medicine_in_next_due_timeframe,
Expand Down Expand Up @@ -33,7 +31,7 @@ def find_reminders(timespan: timedelta):
)
logger.info(f"Found {len(medicines_to_remind)} medicines")

records_to_remind: List[Dict] = []
records_to_remind: list[dict] = []
records_to_remind.extend(appointments_to_remind)
records_to_remind.extend(medicines_to_remind)

Expand Down
6 changes: 3 additions & 3 deletions app/support/notifications.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Dict, Optional, Tuple
from typing import Any, Optional
from datetime import timedelta

from support.common.aws_resources import (
Expand Down Expand Up @@ -47,7 +47,7 @@ def _publish_to_topic(topic: Any, message: str, subject: Optional[str] = None):
"""


def format_reminder_email(records: List[Dict], timespan: timedelta) -> Tuple[str, str]:
def format_reminder_email(records: list[dict], timespan: timedelta) -> tuple[str, str]:
"""
returns -> (subject, message)
"""
Expand All @@ -68,7 +68,7 @@ def format_reminder_email(records: List[Dict], timespan: timedelta) -> Tuple[str
return subject, message


def format_reminder_sms(records: List[Dict], timespan: timedelta) -> str:
def format_reminder_sms(records: list[dict], timespan: timedelta) -> str:
message = f"""
Hello,
These are your reminders for {timespan.days} days, from {current_date()}:
Expand Down
8 changes: 4 additions & 4 deletions app/support/record_formatting.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Callable, List, Dict
from typing import Any, Callable
from logging import Logger
from enum import Enum

Expand Down Expand Up @@ -116,7 +116,7 @@ def str_to_column(self, string: str) -> str:

def format_record_section(self,
section_title: str,
record: Dict,
record: dict,
key: Any,
pre_formatter: Callable[[Any], str] = lambda x: x) -> str:
section_title += ':'
Expand All @@ -136,7 +136,7 @@ def format_record_section(self,
section += '\n'
return section

def format_record(self, record: Dict) -> str:
def format_record(self, record: dict) -> str:
"""formats record into a style resembling a card"""
fr = '' # formatted record
record_type: str = record['record_type'] # record_type is in every record
Expand Down Expand Up @@ -208,7 +208,7 @@ def format_record(self, record: Dict) -> str:
)
return fr

def format_records(self, records: List[Dict]) -> str:
def format_records(self, records: list[dict]) -> str:
"""formats multiple records into a style resembling a card"""
record_cards = []
for record in records:
Expand Down
9 changes: 4 additions & 5 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import yaml
from typing import Dict
from os import environ

from app.support.data_access_layer.put_records import (
Expand All @@ -9,9 +8,9 @@
put_medication_record,
put_observation_record
)
from support.common.aws_resources import get_pet_table_resource
from app.support.common.aws_resources import get_pet_table_resource
from tests.mock_pet_table_data import test_data
from support.common.logger import get_full_logger
from app.support.common.logger import get_full_logger

logger = get_full_logger()

Expand All @@ -20,7 +19,7 @@ def mock_utc_timestamp_now():
return 123456.789


def _get_sam_template() -> Dict:
def _get_sam_template() -> dict:
loader = yaml.Loader
# The following line is some ropey business, just don't access any values
# that are populated by the '!GetAtt' or '!Ref' functions and you'll be fine.
Expand All @@ -33,7 +32,7 @@ def _get_sam_template() -> Dict:
return full_template


def get_pet_table_properties() -> Dict:
def get_pet_table_properties() -> dict:
full_template = _get_sam_template()
# No get functions here, we want this to blow up if it can't find the table
pet_table_properties = full_template['Resources']['PetTable']['Properties']
Expand Down
Loading

0 comments on commit b8fa76d

Please sign in to comment.