Skip to content

Commit

Permalink
🔄 merge: Merge tag '0.2.0-SNAPSHOT'
Browse files Browse the repository at this point in the history
  • Loading branch information
xitowzys committed Mar 16, 2023
2 parents 8208856 + 06ca61f commit 0746570
Show file tree
Hide file tree
Showing 13 changed files with 154 additions and 64 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,5 @@ cython_debug/
test.py
*.ipynb

allureress/
allureress/
main.py
12 changes: 11 additions & 1 deletion fastapi_gateway_auto_generate/Config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -30,4 +38,6 @@ def __init__(
self.__validation_parameters()

def __validation_parameters(self) -> None:
"""_summary_
"""
logger.debug("Validation config parameters")
37 changes: 37 additions & 0 deletions fastapi_gateway_auto_generate/database/DeleteService.py
Original file line number Diff line number Diff line change
@@ -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
38 changes: 38 additions & 0 deletions fastapi_gateway_auto_generate/database/SetMarkDeleteSerivce.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 5 additions & 1 deletion fastapi_gateway_auto_generate/database/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
]
10 changes: 6 additions & 4 deletions fastapi_gateway_auto_generate/database/models/Services.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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]:

Expand All @@ -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
}
2 changes: 1 addition & 1 deletion fastapi_gateway_auto_generate/domain/models/RouteModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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)

Expand All @@ -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
)
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Original file line number Diff line number Diff line change
@@ -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 ###
49 changes: 0 additions & 49 deletions main.py

This file was deleted.

0 comments on commit 0746570

Please sign in to comment.