views.py 1.51 KB
from django.shortcuts import render
from cloud.models import File
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
import boto3
from django.http import JsonResponse
from cloud.aws import aws_key
# class FileToURL(View):
#     s3_client = boto3.client(
#         's3',
#         aws_access_key_id={'AKIAIBBP3XOYSXLBY2IQ'},
#         aws_secret_access_key={'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'}
#     )
#     @csrf_exempt
#     def post(self, request):
#         #FILES=MultiValueDict({'file':['/path1.txt','/folder/path2.txt',...]})
#         for file in request.FILES.getlist('file'):
#             self.s3_client.upload_fileobj(
#                 file,
#                 {'khuloud'},
#                 file.name
#             )
#         file_urls = [f"https://s3.us-ease-1.amazonaws.com/khuloud/{file.name}" for file in request.FILES.getlist('file')]

#         return JsonResponse({'files':file_urls}, status=200)


class FileView(View):
    keys=aws_key()
    s3_client = boto3.client(
        's3',
        aws_access_key_id = keys['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=keys['AWS_SECRET_ACCESS_KEY']
    )
    

    @csrf_exempt
    def post(self, request):
        # filename = request.data.get('filename')
        bucket_name = "khuloud"
        filepath = 'cloud/test/text1.txt'
        self.s3_client.upload_file(filepath, bucket_name, filepath)
        s3link='https://s3.console.aws.amazon.com/s3/buckets/'+bucket_name+'/'+filepath
        return JsonResponse({'file':s3link})