Browse Source

optimize settings

chenhaiyang 4 years ago
parent
commit
1927fafbf9
5 changed files with 61 additions and 58 deletions
  1. 0 10
      app/controllers/targets.py
  2. 41 20
      app/core/config.py
  3. 6 13
      app/main.py
  4. 4 6
      app/services/platform.py
  5. 10 9
      app/services/transfer.py

+ 0 - 10
app/controllers/targets.py

@@ -290,19 +290,12 @@ async def readjust_all_target(project_id: str, space_id: str, wechat_time: str):
         platform = DataPlatformService(client, project_id)
 
         realtime_temperature = await platform.get_realtime_temperature(space_id)
-        logger.debug(realtime_temperature)
         current_targets = await transfer.get_custom_target()
-        logger.debug(current_targets)
         feedback = await transfer.get_feedback(wechat_time)
-        logger.debug(feedback)
         is_customized = await transfer.is_customized()
-        logger.debug(is_customized)
         is_temporary = await transfer.is_temporary()
-        logger.debug(is_temporary)
         season = await transfer.get_season()
-        logger.debug(season)
         previous_changes = await transfer.env_database_get()
-        logger.debug(previous_changes)
 
     if feedback.get('switch off') and feedback.get('switch off') > 0:
         need_switch_off = True
@@ -343,13 +336,10 @@ async def readjust_all_target(project_id: str, space_id: str, wechat_time: str):
             transfer = SpaceInfoService(client, project_id, space_id)
 
             if temperature_results.get('temporary_targets'):
-                logger.debug(temperature_results.get('temporary_targets'))
                 await transfer.set_custom_target('temperature', temperature_results.get('temporary_targets'), '0')
             if temperature_results.get('global_targets'):
-                logger.debug(temperature_results.get('global_targets'))
                 await transfer.set_custom_target('temperature', temperature_results.get('global_targets'), '1')
             if temperature_results.get('latest_change'):
-                logger.debug(temperature_results.get('latest_change'))
                 await transfer.env_database_set('temperature', temperature_results.get('latest_change'))
 
     return need_run_room_control

+ 41 - 20
app/core/config.py

@@ -1,27 +1,48 @@
 # -*- coding: utf-8 -*-
 
-from pathlib import Path
-
-from pydantic import BaseSettings
-
-
-class PlatformSettings(BaseSettings):
-    platform_host: str
-    platform_secret: str
+import secrets
+from typing import Any, Dict, Optional
+
+from pydantic import AnyHttpUrl, BaseSettings, DirectoryPath, PostgresDsn, SecretStr, validator
+
+
+class Settings(BaseSettings):
+    API_V1_STR: str = '/api/v1'
+    SECRET_KEY: str = secrets.token_urlsafe(32)
+    # 60 minutes * 24 hours * 8 days = 8 days
+    ACCESS_TOKEN_MINUTES: int = 60 * 24 * 8
+    # SERVER_NAME: str
+    # SERVER_HOST: AnyHttpUrl
+
+    PLATFORM_HOST: AnyHttpUrl
+    PLATFORM_SECRET: SecretStr
+    TRANSFER_HOST: AnyHttpUrl
+
+    LOGS_DIR: DirectoryPath
+
+    PROJECT_NAME: str
+
+    POSTGRES_SERVER: str
+    POSTGRES_USER: str
+    POSTGRES_PASSWORD: str
+    POSTGRES_DB: str
+    SQLALCHEMY_DATABASE_URI: Optional[PostgresDsn] = None
+
+    @validator('SQLALCHEMY_DATABASE_URI', pre=True)
+    def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
+        if isinstance(v, str):
+            return v
+        return PostgresDsn.build(
+            scheme='postgresql',
+            user=values.get('POSTGRES_USER'),
+            password=values.get('POSTGRES_PASSWORD'),
+            host=values.get('POSTGRES_SERVER'),
+            path=f'/{values.get("POSTGRES_DB") or ""}'
+        )
 
     class Config:
+        case_sensitive = True
         env_file = '.env'
 
 
-class TransferSettings(BaseSettings):
-    transfer_host: str
-
-    class Config:
-        env_file = '.env'
-
-
-class LoggerSettings(BaseSettings):
-    logs_dir: Path
-
-    class Config:
-        env_file = '.env'
+settings = Settings()

+ 6 - 13
app/main.py

@@ -1,20 +1,18 @@
 # -*- coding: utf-8 -*-
 
 import logging
-from functools import lru_cache
 from pathlib import Path
 
 import uvicorn
-from fastapi import FastAPI, Depends
+from fastapi import FastAPI
 from loguru import logger
 
 from app.api.routers import targets, equipment, space
-from app.core.config import LoggerSettings
+from app.core.config import settings
 from app.core.logger import InterceptHandler
 
-logger_settings = LoggerSettings()
 logging.getLogger().handlers = [InterceptHandler()]
-logger.add(Path(logger_settings.logs_dir, 'env_fastapi.log'), level='INFO', rotation='00:00', encoding='utf-8')
+logger.add(Path(settings.LOGS_DIR, 'env_fastapi.log'), level='INFO', rotation='00:00', encoding='utf-8')
 
 app = FastAPI()
 
@@ -23,15 +21,10 @@ app.include_router(space.router, prefix='/room')
 app.include_router(equipment.router, prefix='/equip')
 
 
-@lru_cache()
-def get_settings():
-    return LoggerSettings()
-
-
-@app.get("/info")
-async def info(settings: LoggerSettings = Depends(get_settings)):
+@app.get('/settings')
+async def info():
     return {
-        'logs_dir': settings.logs_dir
+        'logs_dir': settings
     }
 
 

+ 4 - 6
app/services/platform.py

@@ -8,13 +8,11 @@ import numpy as np
 from httpx import AsyncClient, URL
 from loguru import logger
 
-from app.core.config import PlatformSettings
+from app.core.config import settings
 from app.services.service import Service
 from app.utils.date import get_time_str, TIME_FMT
 from app.utils.math import round_half_up
 
-platform_settings = PlatformSettings()
-
 
 class InfoCode(str, Enum):
     temperature = 'Tdb'
@@ -33,13 +31,13 @@ class DataPlatformService(Service):
             self,
             client: AsyncClient,
             project_id: str,
-            settings: PlatformSettings = platform_settings
+            server_settings=settings
     ):
         super(DataPlatformService, self).__init__(client)
         self._project_id = project_id
-        self._base_url = URL(settings.platform_host)
+        self._base_url = URL(server_settings.PLATFORM_HOST)
         self._now_time = get_time_str()
-        self._secret = settings.platform_secret
+        self._secret = server_settings.PLATFORM_SECRET
 
     def _common_parameters(self) -> Dict:
         return {'projectId': self._project_id, 'secret': self._secret}

+ 10 - 9
app/services/transfer.py

@@ -8,12 +8,10 @@ import numpy as np
 import pandas as pd
 from httpx import AsyncClient, URL
 
-from app.core.config import TransferSettings
+from app.core.config import settings
 from app.services.service import Service
 from app.utils.date import get_time_str, TIME_FMT
 
-transfer_settings = TransferSettings()
-
 
 class Season(str, Enum):
     cooling = 'Cooling'
@@ -28,12 +26,12 @@ class SpaceInfoService(Service):
             client: AsyncClient,
             project_id: str,
             space_id: str,
-            settings: TransferSettings = transfer_settings
+            server_settings=settings
     ) -> None:
         super(SpaceInfoService, self).__init__(client)
         self._project_id = project_id
         self._space_id = space_id
-        self._base_url = URL(settings.transfer_host)
+        self._base_url = URL(server_settings.TRANSFER_HOST)
         self._now_time = get_time_str()
 
     def _common_parameters(self) -> Dict:
@@ -108,8 +106,11 @@ class SpaceInfoService(Service):
         params.update({'date': arrow.get(self._now_time, TIME_FMT).date().strftime('%Y%m%d')})
         raw_info = await self._get(url, params)
 
-        custom_target_df = pd.DataFrame(raw_info.get('data'))
-        custom_target_df.set_index('time', inplace=True)
+        try:
+            custom_target_df = pd.DataFrame(raw_info.get('data'))
+            custom_target_df.set_index('time', inplace=True)
+        except KeyError:
+            custom_target_df = pd.DataFrame()
 
         return custom_target_df
 
@@ -184,10 +185,10 @@ class SpaceInfoService(Service):
 
 class EquipmentInfoService(Service):
 
-    def __init__(self, client: AsyncClient, project_id: str, settings: TransferSettings = transfer_settings):
+    def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
         super(EquipmentInfoService, self).__init__(client)
         self._project_id = project_id
-        self._base_url = URL(settings.transfer_host)
+        self._base_url = URL(server_settings.TRANSFER_HOST)
         self._now_time = get_time_str()
 
     async def get_space_by_equipment(self, equipment_id: str) -> List[dict]: