권주희

setting postgres and django project

from django.contrib import admin
from .models import Item, SharedItem, User
admin.site.register(Item)
admin.site.register(SharedItem)
admin.site.register(User)
\ No newline at end of file
# Generated by Django 3.0.7 on 2020-06-04 19:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SharedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('item_id', models.IntegerField()),
('valid', models.DateTimeField()),
('password', models.CharField(max_length=20)),
],
options={
'ordering': ['item_id'],
},
),
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('int_id', models.IntegerField()),
('user_id', models.CharField(max_length=50)),
('name', models.CharField(max_length=50)),
('password', models.CharField(max_length=20)),
('total_size', models.IntegerField()),
('current_size', models.IntegerField()),
],
options={
'ordering': ['int_id'],
},
),
migrations.CreateModel(
name='Item',
fields=[
('item_id', models.IntegerField(primary_key=True, serialize=False)),
('is_folder', models.BooleanField(default=False)),
('name', models.CharField(max_length=50)),
('path', models.TextField()),
('user_id', models.IntegerField()),
('size', models.IntegerField()),
('is_deleted', models.BooleanField(default=False)),
('created_time', models.DateTimeField()),
('updated_time', models.DateTimeField()),
('status', models.BooleanField()),
('parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Item')),
],
options={
'ordering': ['item_id'],
},
),
]
# Generated by Django 3.0.7 on 2020-06-05 09:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='item',
name='parent',
field=models.IntegerField(),
),
]
......@@ -6,7 +6,8 @@ class Item(models.Model):
is_folder = models.BooleanField(default = False)
name = models.CharField(max_length = 50)
path = models.TextField()
parent = models.ForiegnKey(related_naem = 'items', on_delete=models.CASCADE) #related_name
#parent = models.ForeignKey('Item', on_delete=models.CASCADE, null=True) #related_name
parent = models.IntegerField()
user_id = models.IntegerField()
size = models.IntegerField()
is_deleted = models.BooleanField(default = False)
......@@ -23,7 +24,7 @@ class Item(models.Model):
class SharedItem(models.Model):
item_id = models.IntegerField()
#file_id?
valid = models.DateTimeFIeld()
valid = models.DateTimeField()
password = models.CharField(max_length = 20)
class Meta:
......
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from api.models import Item
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
......@@ -10,3 +12,8 @@ class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
......
import mimetypes
import os
import boto3
from django.contrib.auth.models import User, Group
from django.http import HttpResponse, JsonResponse
from rest_framework import viewsets
from rest_framework import permissions
from django.views.decorators.csrf import csrf_exempt
from rest_framework import renderers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated, AllowAny
from api.models import Item
from api.serializers import UserSerializer,GroupSerializer,ItemSerializer
from rest_framework import generics
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
"""
def item_list(request):
if request.method == 'GET':
items = Item.objects.all()
serializer = ItemSerializer(items, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
s3 = boto3.client('s3')
s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
file_name = request.GET['image_name']
file_type = mimetypes.guess_type(file_name)[0]
presigned_post = s3.generate_presigned_post(
Bucket=s3_bucket,
Key=file_name,
Fields={"acl": "private", "Content-Type": file_type},
Conditions=[
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn=3600
)
data = {
"signed_url": presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
}
return presigned_post['url']
def item_detail(request, pk):
try:
item = Item.objects.get(pk=pk)
except Item.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = ItemSerializer(item)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
s3 = boto3.client('s3')
s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
file_name = item.GET['image_name']
file_type = mimetypes.guess_type(file_name)[0]
presigned_post = s3.generate_presigned_post(
Bucket=s3_bucket,
Key=file_name,
Fields={"acl": "private", "Content-Type": file_type},
Conditions=[
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn=3600
)
data = {
"signed_url": presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
}
return presigned_post['url']
elif request.method == 'DELETE':
item.delete()
return HttpResponse(status=204)
"""
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny,
#IsOwnerOrReadOnly
]
# 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 = os.environ.get('AWS_STORAGE_BUCKET_NAME')
s3_bucket = 'arn:aws:s3:::[s3id]'
#file_name = request.GET['image_name']
file_name = request.GET.get('image_name', '')
file_type = mimetypes.guess_type(file_name)[0]
presigned_post = s3.generate_presigned_post(
Bucket=s3_bucket,
Key=file_name,
Fields={"acl": "private", "Content-Type": file_type},
Conditions=[
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn=3600
)
data = {
"signed_url": presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
}
return presigned_post['url']
# url: /status
@action(methods=['POST'], detail=True, permission_classes=[AllowAny],
url_path='status', url_name='status')
def status(self, request):
if request.method == 'POST':
#name = request.POST['name']
name = request.POST.get('name', '')
up_time = request.POST.get('updated_time', '')
try:
item = Item.objects.get(name=name, updated_time=up_time)
except Item.DoesNotExist:
return Response({'Error': 'File Upload Error'}, status=status.HTTP_200_OK)
return Response({'Message': 'File Upload Successful'}, status=status.HTTP_200_OK)
"""
# url: /children
@action(methods=['POST'], detail=True, permission_classes=[AllowAny],
url_path='children', url_name='children')
def children(self, request):
if request.method == 'POST':
#name = request.POST['name']
name = request.POST.get('name', '')
path = request.POST.get('path', '')
parent = request.POST.get('item_id', '')
daughter = Item(name = name, path = path, parent = parent)
daughter.save()
"""
"""
class ItemViewSet(viewsets.ModelViewSet):
#API endpoint that allows groups to be viewed or edited.
queryset = Item.objects.all().order_by('-item_id')
serializer_class = ItemSerializer
permission_classes = [permissions.IsAuthenticated]
def item_list(self, request):
if request.method == 'GET':
items = Item.objects.all()
serializer = ItemSerializer(items, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
s3 = boto3.client('s3')
s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
file_name = request.GET['image_name']
file_type = mimetypes.guess_type(file_name)[0]
presigned_post = s3.generate_presigned_post(
Bucket=s3_bucket,
Key=file_name,
Fields={"acl": "private", "Content-Type": file_type},
Conditions=[
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn=3600
)
data = {
"signed_url": presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
}
return presigned_post['url']
"""
"""
#url: /items/{item_id}/upload
@action(methods=['post'], detail=True, permission_classes=[IsAuthenticated],
url_path='upload', url_name='upload')
def upload(self, request):
s3 = boto3.client('s3')
s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
file_name = request.GET['image_name']
file_type = mimetypes.guess_type(file_name)[0]
presigned_post = s3.generate_presigned_post(
Bucket=s3_bucket,
Key=file_name,
Fields={"acl": "private", "Content-Type": file_type},
Conditions=[
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn=3600
)
data = {
"signed_url": presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
}
return presigned_post['url']
def upload(self, request):
if request.method == 'POST':
serializer = ItemSerializer(data=request.data)
if serializer.is_valid():
BUCKET_NAME = 'presigned-post-example'
KEY_NAME = 'cat.jpg'
s3 = boto3.client('s3')
resp = s3.generate_presigned_post(
Bucket = BUCKET_NAME,
Key = KEY_NAME,
)
resp['fields']['file'] = '@{key}'.format(key=KEY_NAME)
form_values = "\n".join(["-F {key}={value} \\".format(key=key, value=value)
for key, value in resp['fields'].items()])
# authentication_classes = (authentication.SessionAuthentication,)
# permission_classes = [IsAuthenticated, ]
"""
from django.contrib import admin
# Register your models here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from khudrive.api.serializers import UserSerializer,GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class ItemViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
\ No newline at end of file
"""
Django settings for khudrive project.
Generated by 'django-admin startproject' using Django 3.0.6.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
......@@ -20,7 +20,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3b=a99pdbz*48$9$kh@h3tkb*9w-m3vtf8ngyymdzwpl5$emwn'
SECRET_KEY = ')i0_(*4t7k3=rcqp*_i0u((9zbk8q(2(3tk(%$woji-e-37=o*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
......@@ -38,7 +38,7 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
# 'api.apps.ApiConfig',
'api.apps.ApiConfig',
]
MIDDLEWARE = [
......@@ -74,11 +74,18 @@ WSGI_APPLICATION = 'khudrive.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'khuDrive',
'USER': 'jooheekwon',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
......
......@@ -13,20 +13,21 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import include, path
from rest_framework import routers
from khudrive.api import views
from django.contrib import admin
from api import views
from django.conf.urls import url
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.ItemViewSet)
router.register(r'items', views.ItemViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
url(r'^upload/$', views.ItemViewSet.upload, name='upload'),
url(r'^status/$', views.ItemViewSet.status, name='status'),
]
......