refactor(chart): Added docstring in each file and function. Fixed long lines

This commit is contained in:
Данил 2024-12-15 10:51:32 +03:00
parent c5d3d9fe9b
commit ed8cf91558
7 changed files with 190 additions and 30 deletions

View file

@ -1,12 +1,25 @@
import httpx
import yaml
from user_agents import parse as ua_parse
"""
This module provides middleware for integrating Plausible Analytics
into a FastAPI application.
"""
from http import HTTPStatus
config = yaml.safe_load(open('../config.yaml'))
import httpx
from user_agents import parse as ua_parse
from chart.utils.load_config import load_config
config = load_config('config.yaml')
# pylint: disable=too-few-public-methods
class PlausibleAnalytics:
"""
Middleware for sending events to Plausible Analytics.
This middleware intercepts each incoming request, collects metadata such as
user-agent, request path, and response status, and sends it as an event to
Plausible Analytics.
"""
async def __call__(self, request, call_next):
response = await call_next(request)
@ -23,8 +36,10 @@ class PlausibleAnalytics:
"props": {
"method": request.method,
"statusCode": response.status_code,
"browser": f"{user_agent_parsed.browser.family} {user_agent_parsed.browser.version_string}",
"os": f"{user_agent_parsed.os.family} {user_agent_parsed.os.version_string}",
"browser": f"{user_agent_parsed.browser.family} "
f"{user_agent_parsed.browser.version_string}",
"os": f"{user_agent_parsed.os.family} "
f"{user_agent_parsed.os.version_string}",
"source": request.headers.get('referer', 'direct'),
},
}
@ -40,7 +55,12 @@ class PlausibleAnalytics:
"User-Agent": request.headers.get('user-agent', 'unknown'),
},
)
except httpx.RequestError as e:
print(f"Request error while sending event to Plausible: {e}")
except httpx.HTTPStatusError as e:
print(f"HTTP status error while sending event to Plausible: {e}")
# pylint: disable=broad-exception-caught
except Exception as e:
print(f"Error sending event to Plausible: {e}")
print(f"Unexpected error sending event to Plausible: {e}")
return response