From a4cca7cbb981ab673e9539eaba82b58b947f0811 Mon Sep 17 00:00:00 2001 From: Niraj Adhikari Date: Tue, 6 Aug 2024 22:50:09 +0545 Subject: [PATCH] upload dem into s3 --- src/backend/app/projects/project_crud.py | 32 +++++++++++++++++++++- src/backend/app/projects/project_routes.py | 9 ++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/backend/app/projects/project_crud.py b/src/backend/app/projects/project_crud.py index 60bbfc99..751a606b 100644 --- a/src/backend/app/projects/project_crud.py +++ b/src/backend/app/projects/project_crud.py @@ -4,13 +4,43 @@ from loguru import logger as log import shapely.wkb as wkblib from shapely.geometry import shape -from fastapi import HTTPException +from fastapi import HTTPException, UploadFile from app.utils import merge_multipolygon from fmtm_splitter.splitter import split_by_square from fastapi.concurrency import run_in_threadpool from databases import Database from app.models.enums import ProjectStatus from app.utils import generate_slug +from io import BytesIO +from app.s3 import add_obj_to_bucket +from app.config import settings + + +async def upload_dem_to_s3(project_id: uuid.UUID, dem_file: UploadFile) -> str: + """Upload dem into S3. + + Args: + project_id (int): The organisation id in the database. + dem_file (UploadFile): The logo image uploaded to FastAPI. + + Returns: + dem_url(str): The S3 URL for the dem file. + """ + dem_path = f"/{project_id}/dem/dem.tif" + + file_bytes = await dem_file.read() + file_obj = BytesIO(file_bytes) + + add_obj_to_bucket( + settings.S3_BUCKET_NAME, + file_obj, + dem_path, + content_type=dem_file.content_type, + ) + + dem_url = f"{settings.S3_DOWNLOAD_ROOT}/{settings.S3_BUCKET_NAME}{dem_path}" + + return dem_url async def create_project_with_project_info( diff --git a/src/backend/app/projects/project_routes.py b/src/backend/app/projects/project_routes.py index 757873c5..1088104a 100644 --- a/src/backend/app/projects/project_routes.py +++ b/src/backend/app/projects/project_routes.py @@ -17,6 +17,7 @@ from shapely.geometry import shape, mapping from shapely.ops import unary_union + router = APIRouter( prefix=f"{settings.API_PREFIX}/projects", responses={404: {"description": "Not found"}}, @@ -70,6 +71,7 @@ async def delete_project_by_id( @router.post("/create_project", tags=["Projects"]) async def create_project( project_info: project_schemas.ProjectIn, + dem: UploadFile = File(None), db: Database = Depends(database.get_db), user_data: AuthUser = Depends(login_required), ): @@ -78,6 +80,13 @@ async def create_project( project_id = await project_crud.create_project_with_project_info( db, author_id, project_info ) + + # Upload DEM to S3 + dem_url = await project_crud.upload_dem_to_s3(project_id, dem) if dem else None + + # Update dem url to database + await project_crud.update_project_dem_url(db, project_id, dem_url) + if not project_id: raise HTTPException( status_code=HTTPStatus.BAD_REQUEST, detail="Project creation failed"