From 22d31659f5f03deb90f9816fa9d75712983deed7 Mon Sep 17 00:00:00 2001 From: xtaodada Date: Sun, 16 Jun 2024 20:48:35 +0800 Subject: [PATCH] :sparkles: Add Influxdb as core dep --- config.py | 11 +++++++++++ dependence/influxdb.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 dependence/influxdb.py diff --git a/config.py b/config.py index 7a85b0a..73c3a64 100644 --- a/config.py +++ b/config.py @@ -33,6 +33,16 @@ class DatabaseConfig(Settings): env_prefix = "db_" +class InfluxDBConfig(Settings): + host: Optional[str] = None + port: Optional[int] = None + token: Optional[str] = None + org: Optional[str] = None + + class Config(Settings.Config): + env_prefix = "influxdb_" + + class RedisConfig(Settings): host: str = "127.0.0.1" port: int = 6379 @@ -161,6 +171,7 @@ class ApplicationConfig(Settings): reload: ReloadConfig = ReloadConfig() database: DatabaseConfig = DatabaseConfig() + influxdb: InfluxDBConfig = InfluxDBConfig() logger: LoggerConfig = LoggerConfig() webserver: WebServerConfig = WebServerConfig() redis: RedisConfig = RedisConfig() diff --git a/dependence/influxdb.py b/dependence/influxdb.py new file mode 100644 index 0000000..b474b9f --- /dev/null +++ b/dependence/influxdb.py @@ -0,0 +1,37 @@ +import contextlib +from typing import Optional + +from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync +from typing_extensions import Self + +from gram_core.base_service import BaseService +from gram_core.config import ApplicationConfig + +__all__ = ("InfluxDatabase",) + + +class InfluxDatabase(BaseService.Dependence): + @classmethod + def from_config(cls, config: ApplicationConfig) -> Self: + return cls(**config.influxdb.dict()) + + def __init__( + self, + host: Optional[str] = None, + port: Optional[int] = None, + token: Optional[str] = None, + org: Optional[str] = None, + ): + self.host = host + self.port = port + self.token = token + self.org = org + self.url = f"http://{host}:{port}" + self.db_client = InfluxDBClientAsync(url=self.url, token=self.token, org=self.org) + + @contextlib.asynccontextmanager + async def client(self) -> InfluxDBClientAsync: + yield self.db_client + + async def shutdown(self): + await self.db_client.close()