Download app/core/s3.py from Gaykar/CNN: direct link, hf CLI and curl.
- Browser
- Download file 1.5 kB
-
https://huggingface.co/spaces/Gaykar/CNN/resolve/main/app/core/s3.py
- Command line
-
hf download hf://spaces/Gaykar/CNN/app/core/s3.py
-
curl -L -o s3.py https://huggingface.co/spaces/Gaykar/CNN/resolve/main/app/core/s3.py
1.5 kB
| from pathlib import Path | |
| import aioboto3 | |
| from botocore.config import Config | |
| from app.core.config import settings | |
| cfg = { | |
| "endpoint": settings.AWS_ENDPOINT_URL_S3, | |
| "bucket": settings.NEON_BUCKET, | |
| "region": settings.AWS_REGION, | |
| "folder": "mri_scan", | |
| "expires_in": 600, | |
| } | |
| session = aioboto3.Session( | |
| aws_access_key_id=settings.AWS_ACCESS_KEY_ID, | |
| aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, | |
| ) | |
| def s3_client(): | |
| return session.client("s3",endpoint_url=cfg["endpoint"],region_name=cfg["region"],config=Config(signature_version="s3v4")) | |
| def user_prefix(user_id: str) -> str: | |
| return f"{user_id}/{cfg['folder']}/" | |
| def owns_key(user_id: str, file_key: str) -> bool: | |
| return file_key.startswith(user_prefix(user_id)) and ".." not in file_key | |
| async def presigned_download_url(user_id: str, file_key: str) -> dict: | |
| if not owns_key(user_id, file_key): | |
| raise PermissionError("file_key does not belong to this user") | |
| async with s3_client() as s3: | |
| url = await s3.generate_presigned_url( | |
| "get_object", | |
| Params={"Bucket": cfg["bucket"], "Key": file_key}, | |
| ExpiresIn=cfg["expires_in"], | |
| ) | |
| return {"download_url": url} | |
| async def delete_scan(user_id: str, file_key: str) -> None: | |
| if not owns_key(user_id, file_key): | |
| raise PermissionError("file_key does not belong to this user") | |
| async with s3_client() as s3: | |
| await s3.delete_object(Bucket=cfg["bucket"], Key=file_key) | |