77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
from fastapi import APIRouter, Request
|
|
from fastapi.responses import JSONResponse
|
|
import logging
|
|
|
|
|
|
unexpected_error_msg = "Unexpected Error: could not end the process"
|
|
|
|
|
|
def select_count(db_connection, select_statement, returned_object, object_key):
|
|
cursor = db_connection.cursor()
|
|
cursor.execute(select_statement)
|
|
count = cursor.fetchone()[0]
|
|
returned_object[object_key] = count
|
|
return returned_object
|
|
|
|
|
|
def select_daily_count(db_connection, select_statement, returned_object, object_key):
|
|
cursor = db_connection.cursor()
|
|
# Execute query
|
|
cursor.execute(select_statement)
|
|
|
|
# Fetch results
|
|
results = cursor.fetchall()
|
|
|
|
# Convert results to list of dicts
|
|
daily_counts = [{"day": row[0], "counter": row[1]} for row in results]
|
|
|
|
returned_object[object_key] = daily_counts
|
|
return returned_object
|
|
|
|
|
|
class LocalDBRoutes:
|
|
|
|
def __init__(self, connection_db):
|
|
self.connection_db = connection_db
|
|
self.router = APIRouter()
|
|
|
|
self.router.add_api_route(
|
|
"/runs_counter",
|
|
self.runs_count,
|
|
methods=["GET"],
|
|
tags=["Local DB"],
|
|
description="WCAG validator runs counter",
|
|
name="runs counter",
|
|
dependencies=[],
|
|
)
|
|
|
|
logging.info("localdb routes correctly initialized.")
|
|
|
|
async def runs_count(self, request: Request) -> JSONResponse:
|
|
|
|
try:
|
|
table_name = "wcag_validator_results"
|
|
returned_object = {}
|
|
|
|
returned_object = select_count(
|
|
db_connection=self.connection_db,
|
|
select_statement=f"SELECT COUNT(*) FROM {table_name}",
|
|
returned_object=returned_object,
|
|
object_key="counter",
|
|
)
|
|
|
|
returned_object = select_daily_count(
|
|
db_connection=self.connection_db,
|
|
select_statement=f"SELECT DATE(insertion_time) AS day, COUNT(*) AS daily_counter FROM {table_name} GROUP BY day ORDER BY day ASC;",
|
|
returned_object=returned_object,
|
|
object_key="daily_counter",
|
|
)
|
|
|
|
return JSONResponse(content=returned_object, status_code=200)
|
|
|
|
except Exception as e:
|
|
logging.error(unexpected_error_msg + " %s", e)
|
|
return JSONResponse(
|
|
content={"error": unexpected_error_msg}, status_code=500
|
|
)
|