윤창목

models: status default, views: upload;status;get-presigned_url, settings:AWS con…

…figuration(secret), urls added
......@@ -27,3 +27,4 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
.idea
secrets.json
......
......@@ -14,7 +14,7 @@ class Item(models.Model):
is_deleted = models.BooleanField(default = False)
created_time = models.DateTimeField(auto_now=True)
updated_time = models.DateTimeField(null=True)
status = models.BooleanField()
status = models.BooleanField(default=False)
#file = models.FileField(upload_to = \path)
......
......@@ -4,6 +4,7 @@ import os
from datetime import datetime
import boto3
from botocore.client import Config
from django.contrib.auth.models import User
from django.core import serializers
......@@ -18,6 +19,7 @@ from api.models import Item, SharedItem
from api.serializers import UserSerializer,GroupSerializer,ItemSerializer
from rest_framework import status
from annoying.functions import get_object_or_None
from khudrive.settings import AWS_SESSION_TOKEN, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_REGION, AWS_STORAGE_BUCKET_NAME
class UserViewSet(viewsets.ModelViewSet):
"""
......@@ -53,12 +55,52 @@ class ItemViewSet(viewsets.ViewSet):
t['id'] = i['pk']
res.append(t)
return Response({'data': {'list' : res}}, status=status.HTTP_200_OK)
"""
# url: items/11/
# 마지막 slash도 써주어야함
def get(self, request, pk):
#print(pk)
s3 = boto3.client('s3')
s3_bucket = AWS_STORAGE_BUCKET_NAME
#파일 객체 생성
object_name = request.GET.get('name', '')
presigned_url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': s3_bucket,
'Key': object_name},
ExpiresIn = 3600
)
return Response({'message': presigned_url}, status=status.HTTP_200_OK)
"""
# url: items/11/
# 마지막 slash도 써주어야함
def get(self, request, pk):
print(pk)
return Response({'message': "info complete"}, status=status.HTTP_200_OK)
s3 = boto3.client('s3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
aws_session_token=AWS_SESSION_TOKEN,
config=Config(signature_version='s3v4'))
s3_bucket = AWS_STORAGE_BUCKET_NAME
item = Item.objects.filter(item_id=pk)
object_name = item.get().name
data = serializers.serialize("json", item)
json_data = json.loads(data)
presigned_url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': s3_bucket,
'Key': object_name},
ExpiresIn = 3600
)
res = json_data[0]['fields']
res['id']=json_data[0]['pk']
res['signed_url']=presigned_url
return Response({'data': res}, status=status.HTTP_200_OK)
# url: items/11/
# 마지막 slash도 써주어야함
......@@ -149,21 +191,78 @@ class ItemViewSet(viewsets.ViewSet):
url_path='children', url_name='children')
def children(self, request, pk, *args, **kwargs):
if request.method == 'GET':
parent_item = Item.objects.get(pk = pk)
parent_item = Item.objects.get(item_id = pk)
try:
parent_item = get_object_or_404(Item, pk = pk)
except parent_item.DoesNotExist:
return Response({'Error': 'Folder does not exist.'})
items = Item.objects.get(parent = parent_item.pk)
return Response(items)
return Response(items, status=status.HTTP_200_OK)
if request.method == 'POST':
data = JSONParser().parse(request)
serializer = ItemSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors)
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# url: /upload/
@action(methods=['POST'], detail=True, permission_classes=[AllowAny],
url_path='upload', url_name='upload')
def upload(self, request, pk):
if request.method == 'POST':
s3 = boto3.client('s3')
s3_bucket = AWS_STORAGE_BUCKET_NAME
#파일 객체 생성
file_name = request.POST.get('name', '')
file_size = request.POST.get('size', '')
file_parent = pk
file_type = mimetypes.guess_type(file_name)[0]
upload_item = Item(name=file_name, size=file_size, user_id=1, file_type=file_type, parent=file_parent)
upload_item.save()
date_long = datetime.utcnow().strftime('%Y%m%dT000000Z')
presigned_post = s3.generate_presigned_post(
s3_bucket,
file_name,
{
"acl": "private",
"Content-Type": file_type,
'region': AWS_REGION,
'x-amz-algorithm': 'AWS4-HMAC-SHA256',
'x-amz-date': date_long
},
[
{"acl": "private"},
{"Content-Type": file_type},
{'x-amz-algorithm': 'AWS4-HMAC-SHA256'},
{'x-amz-date': date_long}
],
3600
)
data = {
"signed_url": presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
}
return Response({'presigned_post':presigned_post, 'proc_data':data}, status=status.HTTP_200_OK)
# url: /status/
@action(methods=['POST'], detail=True, permission_classes=[AllowAny],
url_path='status', url_name='status')
def status(self, request, *args, **kwargs):
if request.method == 'POST':
pk = request.POST.get('item_id', '')
queryset = Item.objects.filter(item_id = pk)
for cand in queryset:
cand.status = True
cand.save()
return Response({'Message': 'File Upload Successful'}, status=status.HTTP_200_OK)
return Response({'Error': 'No such item found in queryset'}, status=status.HTTP_400_BAD_REQUEST)
......
......@@ -11,10 +11,17 @@ https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
import sys
import json
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_DIR = os.path.dirname(BASE_DIR)
# secrets.json의 경로
SECRETS_PATH = os.path.join(ROOT_DIR, 'secrets.json')
# json파일을 파이썬 객체로 변환
secrets = json.loads(open(SECRETS_PATH).read())
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
......@@ -82,8 +89,8 @@ DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'khuDrive',
'USER': 'jooheekwon',
'PASSWORD': '',
'USER': 'root',
'PASSWORD': '1234',
'HOST': 'localhost',
'PORT': '',
}
......@@ -127,3 +134,11 @@ USE_TZ = True
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
#S3
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
for key, value in secrets.items():
setattr(sys.modules[__name__], key, value)
\ No newline at end of file
......
......@@ -34,5 +34,6 @@ urlpatterns = [
url(r'^<int:pk>/move/$', views.ItemViewSet.move, name='move'),
url(r'^<int:pk>/copy/$', views.ItemViewSet.copy, name='copy'),
url(r'^children/$', views.ItemViewSet.children, name='children'),
url(r'^upload/$', views.ItemViewSet.upload, name='upload'),
url(r'^status/$', views.ItemViewSet.status, name='status'),
]
......