-
Notifications
You must be signed in to change notification settings - Fork 1
CSV file upload #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NXXR
wants to merge
10
commits into
main
Choose a base branch
from
feature/upload-file-forward
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
CSV file upload #15
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
eee6a5b
initil api & controller
NXXR 23fa98f
Merge remote-tracking branch 'origin/main' into feature/upload-file-f…
NXXR 4ac93d0
restructure env vars, add minio client creation
NXXR dbb0511
Merge branch 'main' into feature/upload-file-forward
NXXR 4b33df9
add minio and finish upload
NXXR ececb35
fixed packages libgl1-mesa-glx to libglx-mesa0 when python image was…
NXXR 7a8bb12
add metadata to uploaded file
NXXR 10397e9
Apply suggestions from self review
NXXR 0e3c424
Revert Dockerfile fix
NXXR 50f8103
Merge branch 'main' into feature/upload-file-forward
NXXR File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# coding: utf-8 | ||
|
||
import logging | ||
from typing import List # noqa: F401 | ||
from datetime import date | ||
from pydantic import Field, StrictStr | ||
from typing import List, Optional | ||
from typing_extensions import Annotated | ||
from fastapi import ( # noqa: F401 | ||
APIRouter, | ||
Body, | ||
File, | ||
Path, | ||
Query, | ||
Request, | ||
UploadFile, | ||
) | ||
|
||
from app.controller.utils_controller import UtilsController | ||
|
||
|
||
router = APIRouter() | ||
controller = UtilsController() | ||
|
||
log = logging.getLogger('API.Utils') | ||
logging.basicConfig(level=logging.INFO) | ||
|
||
@router.post( | ||
"/utils/share/casedata", | ||
status_code=202, | ||
tags=["Utils"], | ||
) | ||
async def validate_and_forward_shared_case_data( | ||
request: Request, | ||
file: UploadFile = File(None, description="csv file of case data to share with ESID") | ||
) -> None: | ||
"""Share Case Data with ESID.""" | ||
log.info(f'POST /utils/caseshare received...') | ||
return await controller.handle_case_data_validation_upload(file, request.state) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
# coding: utf-8 | ||
|
||
import logging | ||
from typing import ClassVar, Dict, List, Tuple # noqa: F401 | ||
from datetime import datetime | ||
from json import dumps | ||
from pathlib import Path | ||
from pydantic import Field, StrictBytes, StrictFloat, StrictInt, StrictStr | ||
from typing import Any, Dict, List, Optional, Tuple, Union, Set | ||
from typing_extensions import Annotated | ||
from fastapi import HTTPException, UploadFile | ||
from starlette.datastructures import State | ||
from app.models.user_detail import UserDetail | ||
from core import config | ||
from functools import lru_cache | ||
from minio import Minio | ||
import os | ||
import requests | ||
|
||
log = logging.getLogger('API.Utils') | ||
logging.basicConfig(level=logging.INFO) | ||
|
||
class UtilsController: | ||
|
||
async def handle_case_data_validation_upload( | ||
self, | ||
file: UploadFile, | ||
request_state: State, | ||
) -> None: | ||
"""Validate the upladed file and forward it""" | ||
# Check if actually a csv file | ||
if not file or not file.filename or not file.filename.lower().endswith('.csv'): | ||
raise HTTPException( | ||
status_code=400, | ||
detail='No CSV file sent' | ||
) | ||
# Check mime type | ||
valid_content_types = ['text/csv', 'application/vnd.ms-excel'] | ||
if file.content_type not in valid_content_types: | ||
raise HTTPException( | ||
status_code=400, | ||
detail=f"File has the wrong content type. Accepts {valid_content_types} but got '{file.content_type}'" | ||
) | ||
# Check first line | ||
line = file.file.readline().decode(encoding='utf-8') | ||
num_cols = len(line.split(';')) # This assumes ';' is always used as separator | ||
if num_cols != 76: # This is also assumes the file always hass this magic number of columns | ||
raise HTTPException( | ||
status_code=400, | ||
detail=f"File has the wrong amount of columns. Needs 76 but has '{num_cols}'" | ||
) | ||
|
||
# Validation successful, upload to minio bucket | ||
lha_id: str = request_state.realm | ||
# Get lha display name | ||
lha_name = next((realm['displayName'] for realm in get_realms() if realm['realm'] == lha_id), '') | ||
uploader: UserDetail = request_state.user | ||
|
||
meta = { | ||
'lha': { | ||
'id': lha_id, | ||
'name': lha_name, | ||
}, | ||
'uploader': { | ||
'id': uploader.userId, | ||
'email': uploader.email, | ||
'roles': uploader.role, | ||
}, | ||
'upload_timestamp': datetime.now().isoformat(), | ||
} | ||
|
||
object_path_in_bucket = os.path.join("arrivals", lha_id, file.filename) | ||
log.info(f'uploading \"{file.filename}\" into \"{object_path_in_bucket}\"') | ||
log.info(f'meta info: {meta}') | ||
|
||
client = create_minio_client() | ||
# go to end of stream to read size | ||
file.file.seek(0, os.SEEK_END) | ||
size = file.file.tell() | ||
# reset to start for upload | ||
file.file.seek(0, 0) | ||
try: | ||
result = client.put_object( | ||
bucket_name='private-lha-data', | ||
object_name=object_path_in_bucket, | ||
data=file.file, | ||
length=size, | ||
metadata=meta | ||
) | ||
log.info(f'created: {result.object_name}, etag: {result.etag}, version: {result.version_id}') | ||
except Exception as ex: | ||
log.warning(f'Unable to upload file: {ex}') | ||
raise HTTPException( | ||
status_code=500, | ||
detail='An error occurred during file upload. Check the logs or contact an administrator.' | ||
) | ||
|
||
return None | ||
|
||
@lru_cache | ||
def get_realms() -> List[Any]: | ||
""" | ||
Request realm list from IDP API | ||
""" | ||
result_realms = requests.get(f'{str(config.IDP_API_URL)}/realms') | ||
if result_realms.status_code != 200: | ||
raise HTTPException(status_code=500, detail='IDP API unreachable to request realms') | ||
return result_realms.json() | ||
|
||
|
||
@lru_cache | ||
def create_minio_client() -> Minio: | ||
""" | ||
Create a Minio client to upload to a bucket | ||
""" | ||
client = Minio( | ||
endpoint=str(config.UPLOAD_FORWARD_ENDPOINT), | ||
access_key=str(config.UPLOAD_FORWARD_ACCESS_KEY), | ||
secret_key=str(config.UPLOAD_FORWARD_SECRET_KEY), | ||
) | ||
return client |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,3 +19,5 @@ aiofiles==23.1.0 | |
numpy==1.26.4 | ||
pandas==1.5.3 | ||
h5py==3.10.0 | ||
minio==7.2.15 | ||
requests==2.32.4 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
realm
field is explicit enough because it contains the region name (e.g. lha-koeln). Theid
field consists of the actual UUID used in Keycloak instead. Is it really necessary to include the full name of the LHA?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm
I'm not sure.
I'll check with Mariama to figure out if the realm field is sufficient.
If they need the exact name they probably could look it up themselves from the api 🤔