feat: replace mock S3 presigned URL generation with dynamic boto3 implementation and support for multiple file types
All checks were successful
Deploy Beta (NATIVE) / deploy (push) Successful in 29s
All checks were successful
Deploy Beta (NATIVE) / deploy (push) Successful in 29s
This commit is contained in:
parent
b5a068ae4f
commit
8fdd237eb4
1 changed files with 42 additions and 3 deletions
45
api/views.py
45
api/views.py
|
|
@ -256,9 +256,48 @@ class PresignedUrlView(APIView):
|
|||
if not file_type:
|
||||
return Response({'error': 'file_type is required'}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Generate a simulated S3 presigned URL
|
||||
s3_key = f"suppliers/{request.user.id}/{file_type}_{secrets.token_hex(4)}.jpg"
|
||||
presigned_url = f"https://s3.ap-south-2.amazonaws.com/supplier-docs/{s3_key}?signature=mock_sig"
|
||||
# Determine file extension based on content_type
|
||||
ext = 'jpg'
|
||||
if 'pdf' in content_type:
|
||||
ext = 'pdf'
|
||||
elif 'png' in content_type:
|
||||
ext = 'png'
|
||||
elif 'jpeg' in content_type:
|
||||
ext = 'jpeg'
|
||||
elif 'jpg' in content_type:
|
||||
ext = 'jpg'
|
||||
elif '/' in content_type:
|
||||
ext = content_type.split('/')[-1]
|
||||
|
||||
# Structure: supplierdocument/supplierid/<documentname>/versionname.ext
|
||||
version_name = f"version_{secrets.token_hex(4)}"
|
||||
s3_key = f"supplierdocument/{request.user.id}/{file_type}/{version_name}.{ext}"
|
||||
|
||||
aws_access = os.environ.get('AWS_ACCESS_KEY_ID') or os.environ.get('AWS_ACCESS_KEY')
|
||||
aws_secret = os.environ.get('AWS_SECRET_ACCESS_KEY') or os.environ.get('AWS_SECRET_KEY')
|
||||
bucket_name = os.environ.get('AWS_STORAGE_BUCKET_NAME') or os.environ.get('AWS_BUCKET_NAME') or 'betasupplierdocument-764709663363-ap-south-2-an'
|
||||
region_name = os.environ.get('AWS_REGION', 'ap-south-2')
|
||||
|
||||
if aws_access and aws_secret:
|
||||
try:
|
||||
import boto3
|
||||
s3_client = boto3.client(
|
||||
's3',
|
||||
aws_access_key_id=aws_access,
|
||||
aws_secret_access_key=aws_secret,
|
||||
region_name=region_name
|
||||
)
|
||||
presigned_url = s3_client.generate_presigned_url(
|
||||
'put_object',
|
||||
Params={'Bucket': bucket_name, 'Key': s3_key, 'ContentType': content_type},
|
||||
ExpiresIn=3600
|
||||
)
|
||||
except Exception as e:
|
||||
print("S3 presigned URL generation failed, falling back to mock:", e)
|
||||
presigned_url = f"https://s3.{region_name}.amazonaws.com/{bucket_name}/{s3_key}?signature=mock_sig"
|
||||
else:
|
||||
presigned_url = f"https://s3.{region_name}.amazonaws.com/{bucket_name}/{s3_key}?signature=mock_sig"
|
||||
|
||||
return Response({
|
||||
'presigned_url': presigned_url,
|
||||
's3_key': s3_key
|
||||
|
|
|
|||
Loading…
Reference in a new issue