Commit e711aea6 authored by vidya.m's avatar vidya.m

firstcommit

parents
POSTGRESQL_URI =postgresql://ilensdev:ilens5432@192.168.0.220/downtime_db
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyUnboundLocalVariableInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="scripts.app_config" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (downtime)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/downtime.iml" filepath="$PROJECT_DIR$/.idea/downtime.iml" />
</modules>
</component>
</project>
\ No newline at end of file
[POSTGRESQL]
host=192.168.0.220
port=5432
user = "ilensdev"
password = "ilens5432
\ No newline at end of file
# import pandas as pd
# import sqlalchemy
# import matplotlib.pyplot as plt
#
#
# def get_downtime_data():
# engine = sqlalchemy.create_engine('postgresql://ilensdev:ilens5432@192.168.0.220/downtime_db')
# query = 'SELECT start_time, end_time FROM downtime_log ORDER BY start_time'
# return pd.read_sql_query(query, engine)
#
#
# def downtime_data(data, unit='hour'):
# if unit == 'minute':
# divisor = 60
# elif unit == 'hour':
# divisor = 3600
# else:
# raise ValueError('Invalid unit. Please enter "hour" or "minute".')
#
# data['downtime'] = (data['start_time'].shift(-1) - data['end_time']).dt.total_seconds() / divisor
# data.loc[data.index[-1], 'downtime'] = 0
#
# return data
#
#
# def plot_downtime(data, unit='hour'):
# data['date'] = data['start_time'].dt.date
#
# downtime_per_day = data.groupby('date')['downtime'].sum()
#
# plot_title = f'Downtime by Day ({unit.capitalize()}s)'
# ylabel = unit.capitalize() + 's'
# downtime_per_day.plot(kind='bar', stacked=True, title=plot_title)
#
# plt.xlabel('Date')
# plt.ylabel(ylabel)
# plt.xticks(rotation=90)
# plt.show()
#
#
# def main():
# data = get_downtime_data()
# data = downtime_data(data)
# plot_downtime(data)
#
# data_minute = downtime_data(data, unit='minute')
# plot_downtime(data_minute, unit='minute')
#
#
# if __name__ == '__main__':
# main()
from dotenv import load_dotenv
import uvicorn
from fastapi import FastAPI
from scripts.service.time import router
load_dotenv()
app = FastAPI(title="Downtime Duration")
app.include_router(router)
if __name__ == "__main__":
uvicorn.run("main:app", host='localhost', port=8000)
\ No newline at end of file
from dotenv import load_dotenv
import os
from configparser import ConfigParser
load_dotenv()
config = ConfigParser()
config.read('conf/application.conf')
class Sql:
postgresql: str = os.environ.get("POSTGRESQL_URI")
class Services:
host = config.get("POSTGRESQL", "host")
port = int(config.get("POSTGRESQL", "port"))
\ No newline at end of file
class APIEndpoints:
calculate ="/calculate"
plot = "/plot"
downtime = "/downtime"
\ No newline at end of file
import sqlalchemy
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from scripts.config.app_config import Sql
engine = create_engine(Sql.postgresql)
LocalSession = sessionmaker(bind=engine)
session = LocalSession()
Base = sqlalchemy.orm.declarative_base()
metadata = MetaData()
\ No newline at end of file
from sqlalchemy import MetaData
from scripts.utils.downtime_connection import SqlUtility
metadata = MetaData()
SqlUtility = SqlUtility()
class PostgresqlCollectRecords:
@staticmethod
def get_downtime_data():
try:
data = SqlUtility.get_downtime_data()
return data
except Exception as e:
print(e, "Error detected in fetching the data")
@staticmethod
def downtime_data():
try:
data = SqlUtility.downtime_data()
return data
except Exception as e:
print(e, "Error detected in fetching the data")
@staticmethod
def plot_downtime():
try:
data = SqlUtility.plot_downtime()
return data
except Exception as e:
print(e, "Error detected in fetching the data")
\ No newline at end of file
from typing import Any, Optional
from pydantic import BaseModel
class DefaultResponse(BaseModel):
status: str = "failed"
message: str
data: Optional[Any]
\ No newline at end of file
import logging
from fastapi import APIRouter
from scripts.constants import APIEndpoints
from scripts.core.handler.time import PostgresqlCollectRecords
from scripts.core.schema.responses import DefaultResponse
router = APIRouter(prefix=APIEndpoints.calculate)
handler = PostgresqlCollectRecords()
@router.post(APIEndpoints.calculate)
async def downtime():
try:
data = handler.get_downtime_data()
return DefaultResponse(message="Successfully Calculated", status="success", data=data)
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Fetching Failed due to server error")
@router.post(APIEndpoints.calculate)
async def downtime_data():
try:
data = handler.downtime_data()
return DefaultResponse(message="Successfully Calculated", status="success", data=data)
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Fetching Failed due to server error")
@router.post(APIEndpoints.calculate)
async def plot_downtime():
try:
data = handler.plot_downtime()
return DefaultResponse(message="Successfully Calculated", status="success", data=data)
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Fetching Failed due to server error")
\ No newline at end of file
from matplotlib import pyplot as plt
from sqlalchemy import MetaData
from scripts.core.db.database import session
metadata = MetaData()
class SqlUtility:
@staticmethod
def get_downtime_data() :
try:
query = 'SELECT start_time, end_time FROM downtime_log ORDER BY start_time',session
except Exception as e:
print(e, "Error")
def downtime_data(data, unit='hour'):
try:
if unit == 'minute':
divisor = 60
elif unit == 'hour':
divisor = 3600
else:
raise ValueError('Invalid unit. Please enter "hour" or "minute".')
data['downtime'] = (data['start_time'].shift(-1) - data['end_time']).dt.total_seconds() / divisor
data.loc[data.index[-1], 'downtime'] = 0
return data
except Exception as e:
print(e, "Error")
def plot_downtime(data, unit='hour'):
try:
data['date'] = data['start_time'].dt.date
downtime_per_day = data.groupby('date')['downtime'].sum()
plot_title = f'Downtime by Day ({unit.capitalize()}s)'
ylabel = unit.capitalize() + 's'
downtime_per_day.plot(kind='bar', stacked=True, title=plot_title)
plt.xlabel('Date')
plt.ylabel(ylabel)
plt.xticks(rotation=90)
plt.show()
except Exception as e:
print(e, "Error")
\ No newline at end of file
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