Spaces:
Runtime error
Runtime error
Commit ·
c8a5bbd
1
Parent(s): f2349df
feat: add S3 utility functions for file upload and presigned URL generation
Browse files- app/utilities/s3.py +60 -0
app/utilities/s3.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mimetypes
|
| 2 |
+
|
| 3 |
+
import boto3
|
| 4 |
+
from botocore.config import Config
|
| 5 |
+
from flask import current_app
|
| 6 |
+
from flask_login import current_user
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_s3_client():
|
| 10 |
+
s3_config = Config(
|
| 11 |
+
retries={"max_attempts": 3, "mode": "standard"},
|
| 12 |
+
request_checksum_calculation="when_required",
|
| 13 |
+
response_checksum_validation="when_required",
|
| 14 |
+
s3={"addressing_style": "path"},
|
| 15 |
+
signature_version="s3v4",
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
return boto3.client(
|
| 19 |
+
"s3",
|
| 20 |
+
endpoint_url=current_app.config["S3_ENDPOINT_URL"],
|
| 21 |
+
aws_access_key_id=current_app.config["S3_ACCESS_KEY_ID"],
|
| 22 |
+
aws_secret_access_key=current_app.config["S3_SECRET_KEY"],
|
| 23 |
+
region_name="us-east-1",
|
| 24 |
+
config=s3_config,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def generate_presigned_url(key, expiration=3600):
|
| 29 |
+
s3_client = get_s3_client()
|
| 30 |
+
bucket = current_app.config["S3_BUCKET_NAME"]
|
| 31 |
+
|
| 32 |
+
presigned_url = s3_client.generate_presigned_url(
|
| 33 |
+
"get_object",
|
| 34 |
+
Params={"Bucket": bucket, "Key": key},
|
| 35 |
+
ExpiresIn=expiration,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
return presigned_url
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def upload_to_s3(file, filename, content_type=None):
|
| 42 |
+
s3 = get_s3_client()
|
| 43 |
+
bucket = current_app.config["S3_BUCKET_NAME"]
|
| 44 |
+
|
| 45 |
+
if content_type is None:
|
| 46 |
+
guessed, _ = mimetypes.guess_type(filename)
|
| 47 |
+
content_type = guessed or "application/octet-stream"
|
| 48 |
+
|
| 49 |
+
file_content = file.read()
|
| 50 |
+
file.seek(0)
|
| 51 |
+
|
| 52 |
+
key = f"notes/{current_user.id}/{filename}"
|
| 53 |
+
s3.put_object(
|
| 54 |
+
Bucket=bucket,
|
| 55 |
+
Key=key,
|
| 56 |
+
Body=file_content,
|
| 57 |
+
ContentType=content_type,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
return key
|