diff --git a/.gitignore b/.gitignore index 89f2566..e4f8f8a 100644 --- a/.gitignore +++ b/.gitignore @@ -167,4 +167,5 @@ cython_debug/ test.py *.ipynb -allureress/ \ No newline at end of file +allureress/ +main.py diff --git a/fastapi_gateway_auto_generate/Config.py b/fastapi_gateway_auto_generate/Config.py index 51c84e2..013947c 100644 --- a/fastapi_gateway_auto_generate/Config.py +++ b/fastapi_gateway_auto_generate/Config.py @@ -7,14 +7,22 @@ class Config: + """The configuration class is intended for configuring auto-generat ion of services for the API Gateway. + Args: + fast_api_app (FastAPI): Pointer to your FastAPI application. + service_management (bool): Enable the built-in service manager. + """ + def __init__( self, fast_api_app: FastAPI, service_management: bool = True, - db_path: Optional[str] = None + db_path: Optional[str] = None, + jwt = None ) -> None: self.fast_api_app: FastAPI = fast_api_app self.service_management: bool = service_management + self.jwt = jwt if db_path is None: self.db_path: str = "./database.db" @@ -30,4 +38,6 @@ def __init__( self.__validation_parameters() def __validation_parameters(self) -> None: + """_summary_ + """ logger.debug("Validation config parameters") diff --git a/fastapi_gateway_auto_generate/database/DeleteService.py b/fastapi_gateway_auto_generate/database/DeleteService.py new file mode 100644 index 0000000..4458d0f --- /dev/null +++ b/fastapi_gateway_auto_generate/database/DeleteService.py @@ -0,0 +1,37 @@ +from loguru import logger +from ..management.models import DeleteService as delete_service_model +from .models import Services + +from sqlalchemy.orm import sessionmaker +from sqlalchemy import create_engine +from ..Config import Config + + +class DeleteService(): + + def __init__(self, db_url: str) -> None: + Session: sessionmaker = sessionmaker( + bind=create_engine(db_url)) + self.__session = Session() + + def delete_service(self, delete_service_model: delete_service_model) -> bool: + + # Добавить проверку существование сервиса [Error Code 1] + + try: + # service: Services = Services( + # domain=str(add_service_model.domain), + # port=add_service_model.port, + # name=add_service_model.name_service + # ) + + service = self.__session.query(Services).filter_by(id=delete_service_model.id_service).first() + # print(delete_service_model.id_service) + self.__session.delete(service) + self.__session.commit() + + self.__session.close() + return True + except Exception as e: + logger.debug(f"Ошибка: {str(e)}") + return False diff --git a/fastapi_gateway_auto_generate/database/SetMarkDeleteSerivce.py b/fastapi_gateway_auto_generate/database/SetMarkDeleteSerivce.py new file mode 100644 index 0000000..431549d --- /dev/null +++ b/fastapi_gateway_auto_generate/database/SetMarkDeleteSerivce.py @@ -0,0 +1,38 @@ +from loguru import logger +from ..management.models import DeleteService as delete_service_model +from .models import Services + +from sqlalchemy.orm import sessionmaker +from sqlalchemy import create_engine +from ..Config import Config + + +class SetMarkDeleteService(): + + def __init__(self, db_url: str) -> None: + Session: sessionmaker = sessionmaker( + bind=create_engine(db_url)) + self.__session = Session() + + def set_mark_delete_service(self, delete_service_model: delete_service_model) -> bool: + + # Добавить проверку существование сервиса [Error Code 1] + + try: + # service: Services = Services( + # domain=str(add_service_model.domain), + # port=add_service_model.port, + # name=add_service_model.name_service + # ) + + service = self.__session.query(Services).filter_by(id=delete_service_model.id_service).first() + service.delete = True + # print(delete_service_model.id_service) + # self.__session.delete(service) + self.__session.commit() + + self.__session.close() + return True + except Exception as e: + logger.debug(f"Ошибка: {str(e)}") + return False diff --git a/fastapi_gateway_auto_generate/database/__init__.py b/fastapi_gateway_auto_generate/database/__init__.py index 225ff53..9b58e94 100644 --- a/fastapi_gateway_auto_generate/database/__init__.py +++ b/fastapi_gateway_auto_generate/database/__init__.py @@ -4,10 +4,14 @@ from .GetAllServices import GetAllServices from .StatusService import StatusService from .UrlService import UrlService +from .DeleteService import DeleteService +from .SetMarkDeleteSerivce import SetMarkDeleteService __all__: list[str] = [ "AddService", "GetAllServices", "StatusService", - "UrlService" + "UrlService", + "DeleteService", + "SetMarkDeleteService" ] diff --git a/fastapi_gateway_auto_generate/database/models/Services.py b/fastapi_gateway_auto_generate/database/models/Services.py index 8591745..a439bc8 100644 --- a/fastapi_gateway_auto_generate/database/models/Services.py +++ b/fastapi_gateway_auto_generate/database/models/Services.py @@ -1,7 +1,7 @@ from dataclasses import dataclass from ..SQLAlchemy.declarative_base import Base -from sqlalchemy import Column, INTEGER, TEXT +from sqlalchemy import Column, INTEGER, TEXT, BOOLEAN from sqlalchemy.orm import relationship, backref from typing import Any from loguru import logger @@ -14,12 +14,13 @@ class Services(Base): domain: Column = Column(TEXT, nullable=False) port: Column = Column(INTEGER, nullable=False) name: Column = Column(TEXT, nullable=False, unique=True) + delete: Column = Column(BOOLEAN, nullable=False, default=False) urls: Any = relationship( - "UrlServices", backref=backref("services")) + "UrlServices", cascade='all,delete', backref=backref("services")) status: Any = relationship( - "StatusServices", backref=backref("services")) + "StatusServices", cascade='all,delete', backref=backref("services")) def obj_to_dict(self) -> dict[str, Column]: @@ -40,5 +41,6 @@ def obj_to_dict(self) -> dict[str, Column]: "port": self.port, "name": self.name, "urls": urls, - "status-code": status_code + "status-code": status_code, + "delete": self.delete } diff --git a/fastapi_gateway_auto_generate/domain/models/RouteModel.py b/fastapi_gateway_auto_generate/domain/models/RouteModel.py index b3c83a4..be1b54c 100644 --- a/fastapi_gateway_auto_generate/domain/models/RouteModel.py +++ b/fastapi_gateway_auto_generate/domain/models/RouteModel.py @@ -18,7 +18,7 @@ class RouteModel(): # response_model: Optional[Type[Any]] = None # status_code: Optional[int] = None tags: Optional[List[str]] = None - # dependencies: Optional[Sequence[params.Depends]] = None, + dependencies: str = None, # summary: Optional[str] = None # description: Optional[str] = None # response_description: str = "Successful Response" diff --git a/fastapi_gateway_auto_generate/domain/usecases/BuildRouteModelsUsecase.py b/fastapi_gateway_auto_generate/domain/usecases/BuildRouteModelsUsecase.py index bb72548..47618ae 100644 --- a/fastapi_gateway_auto_generate/domain/usecases/BuildRouteModelsUsecase.py +++ b/fastapi_gateway_auto_generate/domain/usecases/BuildRouteModelsUsecase.py @@ -7,7 +7,7 @@ from pathlib import Path from pprint import pprint from loguru import logger -from fastapi import FastAPI +from fastapi import FastAPI, Depends from ...Config import Config from ..models import RouteModel from ...utils.OpenApiParser import OpenApiParser @@ -79,13 +79,19 @@ def execute(self, config: Config) -> list[dict[str, Any]]: path_method: str = self.__open_api_parser.get_path_method( path) + dependencies = [] + + if not config.jwt is None: + dependencies.append(Depends(config.jwt(service["name"]))) + route_model: RouteModel = RouteModel( request_method=getattr( config.fast_api_app, path_method), gateway_path=f"/{service['name']}{path}", service_url=url, service_path=path, - tags=[service["name"]] + tags=[service["name"]], + dependencies=dependencies ) route_model.query_params, route_model.query_required, route_model.query_is_cookie = self.__open_api_parser.get_queries_param( diff --git a/fastapi_gateway_auto_generate/domain/usecases/BuildRoutesUsecase.py b/fastapi_gateway_auto_generate/domain/usecases/BuildRoutesUsecase.py index adacd34..ebbc131 100644 --- a/fastapi_gateway_auto_generate/domain/usecases/BuildRoutesUsecase.py +++ b/fastapi_gateway_auto_generate/domain/usecases/BuildRoutesUsecase.py @@ -46,11 +46,13 @@ def execute(self, services_result: list[dict[str, Any]], fast_api_app: FastAPI) query_params=route_model.query_params, form_params=route_model.form_params, tags=route_model.tags, - body_params=body_list + body_params=body_list, + dependencies=route_model.dependencies, )(f=func) - UpdateOpenApiSchemaUsecase().execute(fast_api_app=fast_api_app) - DeleteTmpModelsFilesUsecase().execute() + UpdateOpenApiSchemaUsecase().execute(fast_api_app=fast_api_app) + + DeleteTmpModelsFilesUsecase().execute() def __import_model(self, service_model_name: str) -> str: _import: str = f"fastapi_gateway_auto_generate.tmp.models.{service_model_name}" diff --git a/fastapi_gateway_auto_generate/domain/usecases/RefreshServicesUsecase.py b/fastapi_gateway_auto_generate/domain/usecases/RefreshServicesUsecase.py index d938113..2bc7e96 100644 --- a/fastapi_gateway_auto_generate/domain/usecases/RefreshServicesUsecase.py +++ b/fastapi_gateway_auto_generate/domain/usecases/RefreshServicesUsecase.py @@ -1,9 +1,10 @@ -from fastapi_gateway_auto_generate.database import StatusService, UrlService, GetAllServices +from fastapi_gateway_auto_generate.database import StatusService, UrlService, GetAllServices, DeleteService from . import * from ...Config import Config from loguru import logger from ..models import RouteModel from fastapi_gateway_auto_generate.management.models import GetAllInfoServices +from fastapi_gateway_auto_generate.management.models import DeleteService as delete_service_model class RefreshServicesUsecase: @@ -15,6 +16,7 @@ def execute(self, config: Config) -> None: get_all_info_services_model: GetAllInfoServices = GetAllInfoServices( page=1) + services, err = GetAllServices(db_url=config.db_url).get_all_services( get_all_info_services_model=get_all_info_services_model) @@ -33,6 +35,12 @@ def execute(self, config: Config) -> None: del config.fast_api_app.routes[i] logger.debug(r) + if service['delete']: + # print(service['id']) + DeleteService(db_url=config.db_url).delete_service( + delete_service_model=delete_service_model(id_service=service['id']) + ) + services_result = BuildRouteModelsUsecase().execute( config=config ) diff --git a/fastapi_gateway_auto_generate/management/routes/DeleteServiceRoute.py b/fastapi_gateway_auto_generate/management/routes/DeleteServiceRoute.py index f7f718f..c07d549 100644 --- a/fastapi_gateway_auto_generate/management/routes/DeleteServiceRoute.py +++ b/fastapi_gateway_auto_generate/management/routes/DeleteServiceRoute.py @@ -1,3 +1,4 @@ +from fastapi_gateway_auto_generate.database import SetMarkDeleteService as set_mark_delete_service_database from fastapi import APIRouter, Depends from ..models import DeleteService from ...Config import Config @@ -10,4 +11,6 @@ def __init__(self, config: Config) -> None: @self.route.delete("/service", tags=["Service management"]) async def delete_service(delete_service: DeleteService = Depends()) -> dict[str, str]: - return {"data": "Hello World"} + result = set_mark_delete_service_database(db_url=self.__config.db_url).set_mark_delete_service( + delete_service_model=delete_service) + return result diff --git a/fastapi_gateway_auto_generate/migration/versions/239ac7daedc7_initial.py b/fastapi_gateway_auto_generate/migration/versions/239ac7daedc7_initial.py new file mode 100644 index 0000000..8531fcd --- /dev/null +++ b/fastapi_gateway_auto_generate/migration/versions/239ac7daedc7_initial.py @@ -0,0 +1,28 @@ +"""initial + +Revision ID: 239ac7daedc7 +Revises: b462f70d947f +Create Date: 2023-02-28 01:56:31.995973 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '239ac7daedc7' +down_revision = 'b462f70d947f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('services', sa.Column('delete', sa.BOOLEAN(), nullable=False)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('services', 'delete') + # ### end Alembic commands ### diff --git a/main.py b/main.py deleted file mode 100644 index 4f90fe7..0000000 --- a/main.py +++ /dev/null @@ -1,49 +0,0 @@ -from core import FastapiGatewayAutoGenerate -from fastapi import FastAPI -import uvicorn - - -from loguru import logger - - -app = FastAPI() - - -# def reload(): -services_url = ["http://127.0.0.1:7200"] - -services_url_dict = { - "mosgim": "http://127.0.0.1:8082", - "healrinex": "http://10.0.5.93:5577" -} - -config = FastapiGatewayAutoGenerate.Config( - fast_api_app=app, - # db_path="./testdb.db" -) - -autoRG = FastapiGatewayAutoGenerate.FastapiGatewayAutoGenerate( - config=config -) - - -# print("OK") -# autoRG.build_routes() - - -# @app.get("/management/update-services") -# def update_services() -> None: -# reload() - -# # Using FastAPI instance - - -# @app.get("/url-list") -# def get_all_urls(): -# url_list = [{"path": route.path, "name": route.name} -# for route in app.routes] -# return url_list - -if __name__ == "__main__": - # reload() - uvicorn.run(app=app, port=5000, log_level="info")