Skip to content

Commit

Permalink
add delete API for draft templates
Browse files Browse the repository at this point in the history
  • Loading branch information
vedina committed Feb 1, 2024
1 parent 9d08f09 commit 6fc7df2
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 8 deletions.
34 changes: 32 additions & 2 deletions app/api/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,16 @@ def get_baseurl(request : Request):
base_url = base_url.replace("http://", "{}://".format(forwarded_proto))
return base_url

def get_uuid():
return str(uuid.uuid4())

@router.post("/template") # Use router.post instead of app.post
async def convert(request: Request,
background_tasks: BackgroundTasks
):
content_type = request.headers.get("content-type", "").lower()
base_url = get_baseurl(request)
task_id = str(uuid.uuid4())
task_id = get_uuid()
_json = await request.json()
task = Task(
uri=f"{base_url}task/{task_id}",
Expand Down Expand Up @@ -130,7 +132,7 @@ async def get_template(request : Request, uuid: str,format:str = Query(None, des
raise HTTPException(status_code=404, detail="Not found")

@router.get("/template")
async def get_datasets(request : Request,q:str = Query(None)):
async def get_templates(request : Request,q:str = Query(None)):
base_url = get_baseurl(request)
uuids = {}
for filename in os.listdir(TEMPLATE_DIR):
Expand Down Expand Up @@ -159,3 +161,31 @@ async def get_datasets(request : Request,q:str = Query(None)):
uuids[_uuid][tag] = "DRAFT" if tag=="template_status" else "?"

return {"template" : list(uuids.values())}

@router.delete("/template/{uuid}",
responses={
200: {"description": "Template deleted successfully"},
404: {"description": "Template not found"}
}
)
async def delete_template(request: Request,
background_tasks: BackgroundTasks,
uuid: str):
template_path = os.path.join(TEMPLATE_DIR, f"{uuid}.json")
base_url = get_baseurl(request)
task_id = get_uuid()
task = Task(
uri=f"{base_url}task/{task_id}",
id=task_id,
name=f"Delete template {uuid}",
error=None,
policyError=None,
status="Running",
started=int(time.time() * 1000),
completed=None,
result=f"{base_url}task/{task_id}",
errorCause=None
)
tasks_db[task.id] = task
background_tasks.add_task(template_service.delete_template,template_path,task,base_url,task_id)
return task
2 changes: 1 addition & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def cleanup_templates():

scheduler = BackgroundScheduler()
scheduler.add_job(cleanup_tasks, 'interval', minutes=30) # Clean up every 30 minutes
scheduler.add_job(cleanup_templates, 'interval', hours=4) # test, otherwise once a day would be ok
#scheduler.add_job(cleanup_templates, 'interval', hours=4) # test, otherwise once a day would be ok
scheduler.start()

if __name__ == "__main__":
Expand Down
28 changes: 23 additions & 5 deletions app/services/template_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def get_template_xlsx(uuid,force=True):
df_info,df_result,df_raw =bp.get_template_frame(json_blueprint)
bp.iom_format_2excel(file_path_xlsx,df_info,df_result,df_raw)
else:
raise FileNotFoundError(f"Fole not found {uuid}.json")
raise FileNotFoundError(f"File not found {uuid}.json")
return file_path_xlsx

def get_nmparser_config(uuid,force=True):
Expand All @@ -60,7 +60,7 @@ def get_nmparser_config(uuid,force=True):
if os.path.exists(file_path):
with open(file_path, "r") as file:
json_blueprint = json.load(file)
file_path = os.path.join(TEMPLATE_DIR, f"{uuid}.nmparser.json")
file_path = os.path.join(TEMPLATE_DIR, f"{uuid}.json.nmparser")
json_config = bp.get_nmparser_config(json_blueprint)
with open(file_path, 'w') as json_file:
json.dump(json_config, json_file, indent=2)
Expand All @@ -80,7 +80,25 @@ def cleanup(age_hours = 8 ):
last_modified_time = datetime.fromtimestamp(os.path.getmtime(file_name))
# Check if the file is older than age_hours
if last_modified_time < threshold_time:
with open(file_name, 'r') as json_file:
delete_template(file_name)


def delete_template(template_path,task,base_url,uuid):
if os.path.exists(template_path):
json_data = None
try:
with open(template_path, 'r') as json_file:
json_data = json.load(json_file)
if json_data.get('template_status') == 'DRAFT':
os.rename(file_name, "backup_{}".format(file_name))
if (json_data != None) and (json_data.get('template_status') == 'DRAFT'):
os.remove(template_path)
task.status="Completed"
else:
task.status="Error"
task.error = f"Template is finalized, can't be deleted"
except Exception as err:
task.status="Error"
task.error = f"Error deleting template {err}"
task.errorCause = traceback.format_exc()
else:
task.status="Error"
task.error = f"Template not found"

0 comments on commit 6fc7df2

Please sign in to comment.