updated events initializer
This commit is contained in:
0
ApiServices/TemplateService/__init__.py
Normal file
0
ApiServices/TemplateService/__init__.py
Normal file
@@ -1,18 +1,18 @@
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from ApiServices.TemplateService.create_route import RouteRegisterController
|
||||
from ApiServices.TemplateService.endpoints.routes import get_routes
|
||||
from ApiServices.TemplateService.open_api_creator import create_openapi_schema
|
||||
from ApiServices.TemplateService.middlewares.token_middleware import token_middleware
|
||||
from ApiServices.TemplateService.config import template_api_config
|
||||
from ApiServices.TemplateService.initializer.create_route import RouteRegisterController
|
||||
|
||||
from .config import api_config
|
||||
|
||||
|
||||
def create_app():
|
||||
|
||||
application = FastAPI(**template_api_config.api_info)
|
||||
application = FastAPI(**api_config.api_info)
|
||||
# application.mount(
|
||||
# "/application/static",
|
||||
# StaticFiles(directory="application/static"),
|
||||
@@ -20,7 +20,7 @@ def create_app():
|
||||
# )
|
||||
application.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=template_api_config.ALLOW_ORIGINS,
|
||||
allow_origins=api_config.ALLOW_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, FastAPI
|
||||
|
||||
|
||||
class RouteRegisterController:
|
||||
|
||||
def __init__(self, app: FastAPI, router_list: List[APIRouter]):
|
||||
self.router_list = router_list
|
||||
self.app = app
|
||||
|
||||
def register_routes(self):
|
||||
for router in self.router_list:
|
||||
self.app.include_router(router)
|
||||
return self.app
|
||||
@@ -1,14 +1,28 @@
|
||||
from fastapi import APIRouter, Request, Response
|
||||
|
||||
from ApiServices.TemplateService.events.events_setter import event_cluster
|
||||
|
||||
test_template_route = APIRouter(prefix="/test", tags=["Test"])
|
||||
|
||||
|
||||
@test_template_route.get(path="/template", description="Test Template Route")
|
||||
@test_template_route.get(
|
||||
path="/template",
|
||||
description="Test Template Route",
|
||||
operation_id="bb20c8c6-a289-4cab-9da7-34ca8a36c8e5"
|
||||
)
|
||||
def test_template(request: Request, response: Response):
|
||||
"""
|
||||
Test Template Route
|
||||
"""
|
||||
headers = dict(request.headers)
|
||||
event_cluster_matched = event_cluster.match_event(
|
||||
event_keys=[
|
||||
"3f510dcf-9f84-4eb9-b919-f582f30adab1",
|
||||
"9f403034-deba-4e1f-b43e-b25d3c808d39",
|
||||
"b8ec6e64-286a-4f60-8554-7a3865454944"
|
||||
]
|
||||
)
|
||||
event_cluster_matched.example_callable()
|
||||
response.headers["X-Header"] = "Test Header GET"
|
||||
return {
|
||||
"completed": True,
|
||||
|
||||
57
ApiServices/TemplateService/events/template/event.py
Normal file
57
ApiServices/TemplateService/events/template/event.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from ApiServices.TemplateService.initializer.event_clusters import EventCluster, Event
|
||||
|
||||
|
||||
single_event = Event(
|
||||
name="example_event",
|
||||
key="176b829c-7622-4cf2-b474-411e5acb637c",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
description="Example event description",
|
||||
)
|
||||
|
||||
def example_callable():
|
||||
"""
|
||||
Example callable method
|
||||
"""
|
||||
return {
|
||||
"completed": True,
|
||||
"message": "Example callable method 2",
|
||||
"info": {
|
||||
"host": "example_host",
|
||||
"user_agent": "example_user_agent",
|
||||
},
|
||||
}
|
||||
single_event.event_callable = example_callable
|
||||
|
||||
other_event = Event(
|
||||
name="example_event-2",
|
||||
key="176b829c-7622-4cf2-b474-421e5acb637c",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
description="Example event 2 description",
|
||||
)
|
||||
def example_callable_other():
|
||||
"""
|
||||
Example callable method
|
||||
"""
|
||||
return {
|
||||
"completed": True,
|
||||
"message": "Example callable method 1",
|
||||
"info": {
|
||||
"host": "example_host",
|
||||
"user_agent": "example_user_agent",
|
||||
},
|
||||
}
|
||||
other_event.event_callable = example_callable_other
|
||||
|
||||
tokens_in_redis = [
|
||||
"3f510dcf-9f84-4eb9-b919-f582f30adab1",
|
||||
"9f403034-deba-4e1f-b43e-b25d3c808d39",
|
||||
"b8ec6e64-286a-4f60-8554-7a3865454944",
|
||||
"176b829c-7622-4cf2-b474-421e5acb637c",
|
||||
]
|
||||
template_event_cluster = EventCluster(endpoint_uu_id="bb20c8c6-a289-4cab-9da7-34ca8a36c8e5")
|
||||
template_event_cluster.add_event([single_event, other_event])
|
||||
matched_event = template_event_cluster.match_event(event_keys=tokens_in_redis)
|
||||
|
||||
print('event_callable', matched_event.event_callable())
|
||||
0
ApiServices/TemplateService/initializer/__init__.py
Normal file
0
ApiServices/TemplateService/initializer/__init__.py
Normal file
41
ApiServices/TemplateService/initializer/create_route.py
Normal file
41
ApiServices/TemplateService/initializer/create_route.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, FastAPI
|
||||
|
||||
|
||||
class RouteRegisterController:
|
||||
|
||||
def __init__(self, app: FastAPI, router_list: List[APIRouter]):
|
||||
self.router_list = router_list
|
||||
self.app = app
|
||||
|
||||
@staticmethod
|
||||
def add_router_with_event_to_database(route: APIRouter):
|
||||
from Schemas import EndpointRestriction
|
||||
|
||||
with EndpointRestriction.new_session() as db_session:
|
||||
route_path = str(getattr(route, "path"))
|
||||
route_summary = str(getattr(route, "name")) or ""
|
||||
operation_id = str(getattr(route, "operation_id")) or ""
|
||||
if not operation_id:
|
||||
return
|
||||
|
||||
for route_method in [method.lower() for method in getattr(route, "methods")]:
|
||||
restriction = EndpointRestriction.find_or_create(
|
||||
**dict(
|
||||
endpoint_method=route_method,
|
||||
endpoint_name=route_path,
|
||||
endpoint_desc=route_summary.replace("_", " "),
|
||||
endpoint_function=route_summary,
|
||||
operation_uu_id=operation_id, # UUID of the endpoint
|
||||
is_confirmed=True,
|
||||
)
|
||||
)
|
||||
if not restriction.meta_data.created:
|
||||
restriction.endpoint_code = f"AR{str(restriction.id).zfill(3)}"
|
||||
restriction.save(db=db_session)
|
||||
|
||||
def register_routes(self):
|
||||
for router in self.router_list:
|
||||
self.app.include_router(router)
|
||||
self.add_router_with_event_to_database(router)
|
||||
return self.app
|
||||
84
ApiServices/TemplateService/initializer/event_clusters.py
Normal file
84
ApiServices/TemplateService/initializer/event_clusters.py
Normal file
@@ -0,0 +1,84 @@
|
||||
|
||||
class EventCluster:
|
||||
|
||||
def __init__(self, endpoint_uu_id: str):
|
||||
self.endpoint_uu_id = endpoint_uu_id
|
||||
self.events = []
|
||||
|
||||
def add_event(self, list_of_events: list["Event"]):
|
||||
"""
|
||||
Add an event to the cluster
|
||||
"""
|
||||
for event in list_of_events:
|
||||
self.events.append(event)
|
||||
self.events = list(set(self.events))
|
||||
|
||||
def get_event(self, event_key: str):
|
||||
"""
|
||||
Get an event by its key
|
||||
"""
|
||||
|
||||
for event in self.events:
|
||||
if event.key == event_key:
|
||||
return event
|
||||
return None
|
||||
|
||||
def set_events_to_database(self):
|
||||
from Schemas import Events, EndpointRestriction
|
||||
with Events.new_session() as db_session:
|
||||
|
||||
if to_save_endpoint := EndpointRestriction.filter_one(
|
||||
EndpointRestriction.uu_id == self.endpoint_uu_id,
|
||||
db=db_session,
|
||||
).data:
|
||||
for event in self.events:
|
||||
event_obj = Events.find_or_create(
|
||||
function_code=event.key,
|
||||
function_class=event.name,
|
||||
description=event.description,
|
||||
endpoint_id=to_save_endpoint.id,
|
||||
endpoint_uu_id=str(to_save_endpoint.uu_id),
|
||||
is_confirmed=True,
|
||||
active=True,
|
||||
db=db_session,
|
||||
)
|
||||
event_obj.save()
|
||||
print(f'UUID: {event_obj.uu_id} event is saved to {to_save_endpoint.uu_id}')
|
||||
|
||||
def match_event(self, event_keys: list[str]) -> "Event":
|
||||
"""
|
||||
Match an event by its key
|
||||
"""
|
||||
print('set(event_keys)', set(event_keys))
|
||||
print('event.keys', set([event.key for event in self.events]))
|
||||
intersection_of_key: set[str] = set(event_keys) & set([event.key for event in self.events])
|
||||
if not len(intersection_of_key) == 1:
|
||||
raise ValueError(
|
||||
f"Event key not found or multiple matches found: {intersection_of_key}"
|
||||
)
|
||||
return self.get_event(event_key=list(intersection_of_key)[0])
|
||||
|
||||
|
||||
class Event:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
key: str,
|
||||
request_validator: str = None,
|
||||
response_validator: str = None,
|
||||
description: str = "",
|
||||
):
|
||||
self.name = name
|
||||
self.key = key
|
||||
self.request_validator = request_validator
|
||||
self.response_validator = response_validator
|
||||
self.description = description
|
||||
|
||||
|
||||
def event_callable(self):
|
||||
"""
|
||||
Example callable method
|
||||
"""
|
||||
print(self.name)
|
||||
return {}
|
||||
0
ApiServices/TemplateService/services/__init__.py
Normal file
0
ApiServices/TemplateService/services/__init__.py
Normal file
Reference in New Issue
Block a user