generated from Luis/nextjs-python-web-template
added attach with background task
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import sql_crud, sql_db, sql_models
|
||||
@@ -139,8 +139,11 @@ def get_repository(
|
||||
@router.post("/api/v1/create_entity", response_model=Entity, tags=[Tags.entities])
|
||||
def create_entity(
|
||||
entity: EntityCreate, db: Session = Depends(sql_db.get_db)
|
||||
) -> EntityCreate:
|
||||
) -> EntityCreate | str:
|
||||
# todo checken ob schon da ...
|
||||
if sql_crud.get_entity_by_did(db, did=entity.did):
|
||||
print("did already exsists")
|
||||
return "Error did already exsists in db"
|
||||
return sql_crud.create_entity(db, entity)
|
||||
|
||||
|
||||
@@ -161,3 +164,17 @@ def get_entity(
|
||||
) -> Optional[sql_models.Entity]:
|
||||
entity = sql_crud.get_entity_by_did(db, did=entity_did)
|
||||
return entity
|
||||
|
||||
|
||||
@router.get("/api/v1/attach", response_model=Optional[Entity], tags=[Tags.entities])
|
||||
async def attach(
|
||||
background_tasks: BackgroundTasks,
|
||||
entity_did: str = "did:sov:test:1234",
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(sql_db.get_db),
|
||||
) -> dict[str, str]:
|
||||
background_tasks.add_task(
|
||||
sql_crud.check_health, db, entity_did, message="Not attched any more"
|
||||
)
|
||||
return {"message": "Attaching in the background"}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -136,3 +137,21 @@ def get_entities(
|
||||
|
||||
def get_entity_by_did(db: Session, did: str) -> Optional[sql_models.Entity]:
|
||||
return db.query(sql_models.Entity).filter(sql_models.Entity.did == did).first()
|
||||
|
||||
|
||||
def check_health(db: Session, entity_did: str, message: str) -> str:
|
||||
# ste attached to true
|
||||
db_entity = get_entity_by_did(db, entity_did)
|
||||
if db_entity is not None:
|
||||
# db_entity.attached = Column(True)
|
||||
setattr(db_entity, "attached", True)
|
||||
# save changes in db
|
||||
db.add(db_entity)
|
||||
db.commit()
|
||||
db.refresh(db_entity)
|
||||
# check every 5 secounds if status has changed
|
||||
while db_entity.attached:
|
||||
time.sleep(5)
|
||||
return f"{entity_did} message"
|
||||
else:
|
||||
return f"{entity_did} not found and not attached"
|
||||
|
||||
Reference in New Issue
Block a user