Skip to content

Commit

Permalink
feat: Add error log to dynamodb controller
Browse files Browse the repository at this point in the history
  • Loading branch information
MissterHao committed Feb 10, 2023
1 parent 47bde4b commit c7a6ba7
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 23 deletions.
11 changes: 9 additions & 2 deletions dysession/aws/dynamodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
SessionKeyDuplicated,
)
from dysession.backends.model import SessionDataModel
from dysession.logger import get_logger

from ..settings import get_config

Expand Down Expand Up @@ -58,7 +59,7 @@ def check_dynamodb_table_exists(table_name: Optional[str] = None, client=None) -

response = client.list_tables()
if table_name not in response["TableNames"]:
raise DynamodbTableNotFound
raise DynamodbTableNotFound(table_name)

return response

Expand Down Expand Up @@ -128,6 +129,8 @@ def insert_session_item(
table_name = get_config()["DYNAMODB_TABLENAME"]

if not ignore_duplicated and key_exists(data.session_key):
logger = get_logger()
logger.error(f"'{data.session_key}' is already an item of table '{table_name}'.")
raise SessionKeyDuplicated

resource = boto3.resource("dynamodb", region_name=get_config()["DYNAMODB_REGION"])
Expand Down Expand Up @@ -200,9 +203,13 @@ def get(
raise SessionExpired
# if not found then raise
except DynamodbItemNotFound:
logger = get_logger()
logger.error(f"'{session_key}' cannot be found on table '{table_name}'.")
raise SessionKeyDoesNotExist
# if key is expired
except SessionExpired:
logger = get_logger()
logger.error(f"'{session_key}' is expired .")
raise SessionExpired

return model
Expand Down Expand Up @@ -236,7 +243,7 @@ def exists(self, session_key: str) -> bool:
def delete(self, data: SessionDataModel, table_name: Optional[str] = None) -> bool:
if data.session_key is None:
return

try:
delete_session_item(data=data, table_name=table_name)
except AssertionError:
Expand Down
14 changes: 12 additions & 2 deletions dysession/aws/error.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from typing import Optional

from dysession.logger import get_logger


class DynamodbTableNotFound(Exception):
pass
def __init__(self, table_name: Optional[str] = None, *args: object) -> None:
super().__init__(*args)

logger = get_logger()
if table_name:
logger.error(f"'{table_name}' is not found in current region.")


class DynamodbItemNotFound(Exception):
pass
pass
1 change: 1 addition & 0 deletions dysession/logger/handler/colorful_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
logging.DEBUG: ANSIColor.DEBUG.value,
logging.INFO: ANSIColor.OKCYAN.value,
logging.WARNING: ANSIColor.WARNING.value,
logging.ERROR: ANSIColor.FAIL.value,
logging.CRITICAL: ANSIColor.FAIL.value,
logging.FATAL: ANSIColor.FAIL.value,
}
Expand Down
4 changes: 1 addition & 3 deletions dysession/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,4 @@ def process_request(self, request):
# SESSION_COOKIE_NAME can be change by developers
# https://docs.djangoproject.com/en/3.2/ref/settings/#session-cookie-name
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
request.session = self.SessionStore(
session_key=session_key,
)
request.session = self.SessionStore(session_key=session_key)
2 changes: 1 addition & 1 deletion dysession/version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.3
1.1.0
8 changes: 8 additions & 0 deletions tests/test_aws_dynamodb.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

import boto3
from django.test import TestCase
from moto import mock_dynamodb
Expand All @@ -18,6 +20,12 @@


class AWSDynamoDBTestCase(TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)

def tearDown(self):
logging.disable(logging.NOTSET)

@mock_dynamodb
def test_init_dynamodb_table(self):

Expand Down
12 changes: 8 additions & 4 deletions tests/test_backend_db.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import time
from datetime import datetime
from typing import Any
Expand All @@ -11,10 +12,8 @@
DynamoDB,
check_dynamodb_table_exists,
create_dynamodb_table,
destory_dynamodb_table,
get_item,
insert_session_item,
key_exists,
)
from dysession.aws.error import DynamodbItemNotFound, DynamodbTableNotFound
from dysession.backends.error import (
Expand All @@ -27,6 +26,12 @@


class DynamoDBTestCase(TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)

def tearDown(self):
logging.disable(logging.NOTSET)

@mock_dynamodb
def create_dynamodb_table(self):
self.options = {
Expand Down Expand Up @@ -266,7 +271,6 @@ def test_delete_item_via_dynamodb_controller_raise_error(self):
with self.assertRaises(AssertionError):
db.delete(model)


@mock_dynamodb
def test_delete_item_via_dynamodb_controller_with_none_type_session_key(self):

Expand All @@ -279,4 +283,4 @@ def test_delete_item_via_dynamodb_controller_with_none_type_session_key(self):
model.session_key = None

db = DynamoDB(self.client)
db.delete(model)
db.delete(model)
22 changes: 11 additions & 11 deletions tests/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
class LoggerTestCase(TestCase):
def test_get_logger_with_second_logger_type_passed_in(self):

with self.assertLogs("dysession") as cm:
logger = get_logger()
with self.assertLogs("test_get_logger_with_second_logger_type_passed_in") as cm:
logger = get_logger("test_get_logger_with_second_logger_type_passed_in")
logger.info("This is a test content")
self.assertIn("This is a test content", "\n".join(cm.output))

with self.assertLogs("dysession") as cm:
logger = get_logger(logger_type=LoggingType.FILE)
with self.assertLogs("test_get_logger_with_second_logger_type_passed_in") as cm:
logger = get_logger("test_get_logger_with_second_logger_type_passed_in", logger_type=LoggingType.FILE)
logger.info("This is a test content")
self.assertIn("WARNING", "\n".join(cm.output))

Expand All @@ -27,9 +27,9 @@ def test_logger_is_tty_handlers(self, mock_is_tty):
is_tty.cache_clear()
mock_is_tty.return_value = True

logger = get_logger()
logger = get_logger("test_logger_is_tty_handlers")
self.assertEqual(len(logger.handlers), 1)
self.assertEqual(logger.name, "dysession")
self.assertEqual(logger.name, "test_logger_is_tty_handlers")
self.assertIs(type(logger.handlers[0]), ColorfulConsoleLoggerHandler)

logger.handlers = []
Expand All @@ -39,22 +39,22 @@ def test_logger_is_not_tty_handlers(self, mock_is_tty):
is_tty.cache_clear()
mock_is_tty.return_value = False

logger = get_logger()
logger = get_logger("test_logger_is_not_tty_handlers")
self.assertEqual(len(logger.handlers), 1)
self.assertEqual(logger.name, "dysession")
self.assertEqual(logger.name, "test_logger_is_not_tty_handlers")
self.assertIs(type(logger.handlers[0]), logging.StreamHandler)

logger.handlers = []

def test_logger_file_handler(self):

logger = get_logger(logger_type=LoggingType.FILE)
logger = get_logger("test_logger_file_handler", logger_type=LoggingType.FILE)

self.assertEqual(len(logger.handlers), 1)
self.assertEqual(logger.name, "dysession")
self.assertEqual(logger.name, "test_logger_file_handler")
self.assertIsInstance(logger.handlers[0], logging.FileHandler)

with self.assertLogs("dysession") as cm:
with self.assertLogs("test_logger_file_handler") as cm:
logger.info("This is a test content")
self.assertIn("This is a test content", "\n".join(cm.output))

Expand Down

0 comments on commit c7a6ba7

Please sign in to comment.