Commit f03e3f23 authored by arjun.b's avatar arjun.b

abstract factory implementation in fastapi

parent 6233d1a0
import uvicorn
from scripts.logging.logging import logger
if __name__ == "__main__":
try:
uvicorn.run("main:app", port=8765)
except Exception as e:
logger.error(e)
print(e)
[log_file_path1]
file_name=scripts/external/logging_log
\ No newline at end of file
import uvicorn
from fastapi import FastAPI
from scripts.logging.logging import logger
from scripts.services.area import shape
app = FastAPI()
app.include_router(shape)
if __name__ == "__main__":
try:
uvicorn.run(app, port=8765)
except Exception as e:
logger.error(e)
print(e)
import configparser
try:
config = configparser.ConfigParser()
config.read("conf/application.conf")
# logging file path
file_name = config.get("log_file_path1", "file_name")
except configparser.NoOptionError as e:
print(f"could not find conf file {e}")
\ No newline at end of file
class EndPoints:
circle_area = "/circle_area"
rectangle_area = "/rectangle_area"
from abc import ABC, abstractmethod
from math import pi
# Abstract factory interface
class AbstractShapeFactory(ABC):
@abstractmethod
def create_shape(self):
pass
# Concrete factory for creating circles
class CircleFactory(AbstractShapeFactory):
def create_shape(self, radius: float):
return Circle(radius)
# Concrete factory for creating rectangles
class RectangleFactory(AbstractShapeFactory):
def create_shape(self, width: float, height: float):
return Rectangle(width, height)
# Abstract product interface
class AbstractShape(ABC):
@abstractmethod
def area(self):
pass
# Concrete product class for circles
class Circle(AbstractShape):
def __init__(self, radius: float):
self.radius = radius
def area(self):
return pi * self.radius ** 2
# Concrete product class for rectangles
class Rectangle(AbstractShape):
def __init__(self, width: float, height: float):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Client code that uses the abstract factory
class AreaCalculator:
def __init__(self, factory: AbstractShapeFactory, *args):
self.shape = factory.create_shape(*args)
def calculate_area(self):
return self.shape.area()
import logging
import os
from logging.handlers import RotatingFileHandler
from scripts.config.application_config import file_name
def get_logger():
"""
Creates a rotating log
"""
__logger__ = logging.getLogger('')
__logger__.setLevel("ERROR")
log_formatter = '%(asctime)s - %(levelname)-6s - [%(threadName)5s:%(funcName)5s():%(lineno)s] - %(message)s'
time_format = "%Y-%m-%d %H:%M:%S"
formatter = logging.Formatter(log_formatter, time_format)
log_file = os.path.join(f"{file_name}_ERROR.log")
temp_handler = RotatingFileHandler(log_file,
maxBytes=100000000,
backupCount=5)
temp_handler.setFormatter(formatter)
__logger__.addHandler(temp_handler)
return __logger__
logger = get_logger()
from fastapi import APIRouter
from scripts.constants.endpoints import EndPoints
from scripts.core.handlers.shape_handler import CircleFactory, AreaCalculator, RectangleFactory
shape = APIRouter()
# Register endpoints that use the abstract factory
@shape.get(EndPoints.circle_area, tags=["Area of a Circle"])
async def circle_area(radius: float):
factory = CircleFactory()
calculator = AreaCalculator(factory, radius)
return {"area": calculator.calculate_area()}
@shape.get(EndPoints.rectangle_area, tags=["Area of a Rectangle"])
async def rectangle_area(width: float, height: float):
factory = RectangleFactory()
calculator = AreaCalculator(factory, width, height)
return {"area": calculator.calculate_area()}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment