Skip to content

Commit

Permalink
Added type hinting to the model
Browse files Browse the repository at this point in the history
  • Loading branch information
rofrano committed Mar 2, 2024
1 parent d0a56f2 commit 8c70be1
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions service/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""
import os
import logging
from typing import List, Optional, Self
from redis import Redis
from redis.exceptions import ConnectionError as RedisConnectionError

Expand All @@ -41,23 +42,29 @@ class Counter:
This follows the same standards as SQLAlchemy URIs
"""

redis = None
redis: Redis = None

def __init__(self, name: str = "hits", value: int = None):
"""Constructor"""
"""Constructor
:param name: Name of the counter (default is "hits")
:type name: str
:param value: Initial value of the counter (default is None)
:type value: int or None
"""
self.name = name
if not value:
self.value = 0
else:
self.value = value

@property
def value(self):
def value(self) -> int:
"""Returns the current value of the counter"""
return int(Counter.redis.get(self.name))

@value.setter
def value(self, value):
def value(self, value: int):
"""Sets the value of the counter"""
Counter.redis.set(self.name, value)

Expand All @@ -66,11 +73,11 @@ def value(self):
"""Removes the counter fom the database"""
Counter.redis.delete(self.name)

def increment(self):
def increment(self) -> int:
"""Increments the current value of the counter by 1"""
return Counter.redis.incr(self.name)

def serialize(self):
def serialize(self) -> dict:
"""Converts a counter into a dictionary"""
return {
"name": self.name,
Expand All @@ -82,7 +89,7 @@ def serialize(self):
######################################################################

@classmethod
def all(cls):
def all(cls) -> List[Self]:
"""Returns all of the counters"""
try:
counters = [
Expand All @@ -94,7 +101,7 @@ def all(cls):
return counters

@classmethod
def find(cls, name):
def find(cls, name: str) -> Self:
"""Finds a counter with the name or returns None"""
counter = None
try:
Expand All @@ -106,7 +113,7 @@ def find(cls, name):
return counter

@classmethod
def remove_all(cls):
def remove_all(cls) -> None:
"""Removes all of the keys in the database"""
try:
cls.redis.flushall()
Expand All @@ -118,7 +125,7 @@ def remove_all(cls):
######################################################################

@classmethod
def test_connection(cls):
def test_connection(cls) -> bool:
"""Test connection by pinging the host"""
success = False
try:
Expand All @@ -130,7 +137,7 @@ def test_connection(cls):
return success

@classmethod
def connect(cls, database_uri=None):
def connect(cls, database_uri: Optional[str] = None):
"""Established database connection
Arguments:
Expand Down

0 comments on commit 8c70be1

Please sign in to comment.