views.py 2.04 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
import configparser

config = configparser.ConfigParser()
config.read('config.ini')
# class FileToURL(View):
#     s3_client = boto3.client(
#         's3',
#         aws_access_key_id={''},
#         aws_secret_access_key={''}
#     )
#     @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')]
class FileView(View):
    #keys=aws_key()
    s3_client = boto3.client(
        's3',
        aws_access_key_id = config['aws']['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY']
    )
    @csrf_exempt
    def post(self, request):
        # filename = request.data.get('filename')
        bucket_name = "test-cloudcomputer"
        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})
    @csrf_exempt
    def create_bucket(self,request):
            """
            s3 = boto3.resource('s3',
            aws_access_key_id = config['aws']['AWS_ACCESS_KEY_ID'],
            aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY']
            )
            """
            bucket=self.s3_client.create_bucket(
                    ACL='public-read-write',
                    Bucket=request.POST['username'],
                    CreateBucketConfiguration={
                            'LocationConstraint':'ap-northeast-2'},
            )