권주희

setting postgres and django project

1 +from django.contrib import admin
2 +
3 +from .models import Item, SharedItem, User
4 +
5 +admin.site.register(Item)
6 +admin.site.register(SharedItem)
7 +admin.site.register(User)
...\ No newline at end of file ...\ No newline at end of file
1 +# Generated by Django 3.0.7 on 2020-06-04 19:52
2 +
3 +from django.db import migrations, models
4 +import django.db.models.deletion
5 +
6 +
7 +class Migration(migrations.Migration):
8 +
9 + initial = True
10 +
11 + dependencies = [
12 + ]
13 +
14 + operations = [
15 + migrations.CreateModel(
16 + name='SharedItem',
17 + fields=[
18 + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 + ('item_id', models.IntegerField()),
20 + ('valid', models.DateTimeField()),
21 + ('password', models.CharField(max_length=20)),
22 + ],
23 + options={
24 + 'ordering': ['item_id'],
25 + },
26 + ),
27 + migrations.CreateModel(
28 + name='User',
29 + fields=[
30 + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
31 + ('int_id', models.IntegerField()),
32 + ('user_id', models.CharField(max_length=50)),
33 + ('name', models.CharField(max_length=50)),
34 + ('password', models.CharField(max_length=20)),
35 + ('total_size', models.IntegerField()),
36 + ('current_size', models.IntegerField()),
37 + ],
38 + options={
39 + 'ordering': ['int_id'],
40 + },
41 + ),
42 + migrations.CreateModel(
43 + name='Item',
44 + fields=[
45 + ('item_id', models.IntegerField(primary_key=True, serialize=False)),
46 + ('is_folder', models.BooleanField(default=False)),
47 + ('name', models.CharField(max_length=50)),
48 + ('path', models.TextField()),
49 + ('user_id', models.IntegerField()),
50 + ('size', models.IntegerField()),
51 + ('is_deleted', models.BooleanField(default=False)),
52 + ('created_time', models.DateTimeField()),
53 + ('updated_time', models.DateTimeField()),
54 + ('status', models.BooleanField()),
55 + ('parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Item')),
56 + ],
57 + options={
58 + 'ordering': ['item_id'],
59 + },
60 + ),
61 + ]
1 +# Generated by Django 3.0.7 on 2020-06-05 09:51
2 +
3 +from django.db import migrations, models
4 +
5 +
6 +class Migration(migrations.Migration):
7 +
8 + dependencies = [
9 + ('api', '0001_initial'),
10 + ]
11 +
12 + operations = [
13 + migrations.AlterField(
14 + model_name='item',
15 + name='parent',
16 + field=models.IntegerField(),
17 + ),
18 + ]
...@@ -6,7 +6,8 @@ class Item(models.Model): ...@@ -6,7 +6,8 @@ class Item(models.Model):
6 is_folder = models.BooleanField(default = False) 6 is_folder = models.BooleanField(default = False)
7 name = models.CharField(max_length = 50) 7 name = models.CharField(max_length = 50)
8 path = models.TextField() 8 path = models.TextField()
9 - parent = models.ForiegnKey(related_naem = 'items', on_delete=models.CASCADE) #related_name 9 + #parent = models.ForeignKey('Item', on_delete=models.CASCADE, null=True) #related_name
10 + parent = models.IntegerField()
10 user_id = models.IntegerField() 11 user_id = models.IntegerField()
11 size = models.IntegerField() 12 size = models.IntegerField()
12 is_deleted = models.BooleanField(default = False) 13 is_deleted = models.BooleanField(default = False)
...@@ -23,7 +24,7 @@ class Item(models.Model): ...@@ -23,7 +24,7 @@ class Item(models.Model):
23 class SharedItem(models.Model): 24 class SharedItem(models.Model):
24 item_id = models.IntegerField() 25 item_id = models.IntegerField()
25 #file_id? 26 #file_id?
26 - valid = models.DateTimeFIeld() 27 + valid = models.DateTimeField()
27 password = models.CharField(max_length = 20) 28 password = models.CharField(max_length = 20)
28 29
29 class Meta: 30 class Meta:
......
1 from django.contrib.auth.models import User, Group 1 from django.contrib.auth.models import User, Group
2 from rest_framework import serializers 2 from rest_framework import serializers
3 +from api.models import Item
4 +
3 5
4 class UserSerializer(serializers.HyperlinkedModelSerializer): 6 class UserSerializer(serializers.HyperlinkedModelSerializer):
5 class Meta: 7 class Meta:
...@@ -10,3 +12,8 @@ class GroupSerializer(serializers.HyperlinkedModelSerializer): ...@@ -10,3 +12,8 @@ class GroupSerializer(serializers.HyperlinkedModelSerializer):
10 class Meta: 12 class Meta:
11 model = Group 13 model = Group
12 fields = ['url', 'name'] 14 fields = ['url', 'name']
15 +
16 +class ItemSerializer(serializers.ModelSerializer):
17 + class Meta:
18 + model = Item
19 + fields = '__all__'
......
1 +import mimetypes
2 +import os
3 +import boto3
4 +
5 +from django.contrib.auth.models import User, Group
6 +from django.http import HttpResponse, JsonResponse
7 +from rest_framework import viewsets
8 +from rest_framework import permissions
9 +from django.views.decorators.csrf import csrf_exempt
10 +from rest_framework import renderers
11 +from rest_framework.views import APIView
12 +from rest_framework.response import Response
13 +from rest_framework.decorators import action
14 +from rest_framework.parsers import JSONParser
15 +from rest_framework.permissions import IsAuthenticated, AllowAny
16 +
17 +from api.models import Item
18 +from api.serializers import UserSerializer,GroupSerializer,ItemSerializer
19 +from rest_framework import generics
20 +
21 +
22 +class UserViewSet(viewsets.ModelViewSet):
23 + """
24 + API endpoint that allows users to be viewed or edited.
25 + """
26 + queryset = User.objects.all().order_by('-date_joined')
27 + serializer_class = UserSerializer
28 + permission_classes = [permissions.IsAuthenticated]
29 +
30 +"""
31 +def item_list(request):
32 + if request.method == 'GET':
33 + items = Item.objects.all()
34 + serializer = ItemSerializer(items, many=True)
35 + return JsonResponse(serializer.data, safe=False)
36 + elif request.method == 'POST':
37 + s3 = boto3.client('s3')
38 + s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
39 + file_name = request.GET['image_name']
40 + file_type = mimetypes.guess_type(file_name)[0]
41 + presigned_post = s3.generate_presigned_post(
42 + Bucket=s3_bucket,
43 + Key=file_name,
44 + Fields={"acl": "private", "Content-Type": file_type},
45 + Conditions=[
46 + {"acl": "public-read"},
47 + {"Content-Type": file_type}
48 + ],
49 + ExpiresIn=3600
50 + )
51 +
52 + data = {
53 + "signed_url": presigned_post,
54 + 'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
55 + }
56 + return presigned_post['url']
57 +
58 +def item_detail(request, pk):
59 + try:
60 + item = Item.objects.get(pk=pk)
61 + except Item.DoesNotExist:
62 + return HttpResponse(status=404)
63 +
64 + if request.method == 'GET':
65 + serializer = ItemSerializer(item)
66 + return JsonResponse(serializer.data)
67 +
68 + elif request.method == 'PUT':
69 + s3 = boto3.client('s3')
70 + s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
71 + file_name = item.GET['image_name']
72 + file_type = mimetypes.guess_type(file_name)[0]
73 + presigned_post = s3.generate_presigned_post(
74 + Bucket=s3_bucket,
75 + Key=file_name,
76 + Fields={"acl": "private", "Content-Type": file_type},
77 + Conditions=[
78 + {"acl": "public-read"},
79 + {"Content-Type": file_type}
80 + ],
81 + ExpiresIn=3600
82 + )
83 + data = {
84 + "signed_url": presigned_post,
85 + 'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
86 + }
87 + return presigned_post['url']
88 +
89 + elif request.method == 'DELETE':
90 + item.delete()
91 + return HttpResponse(status=204)
92 +"""
93 +
94 +
95 +class ItemViewSet(viewsets.ModelViewSet):
96 +
97 + queryset = Item.objects.all()
98 + serializer_class = ItemSerializer
99 + permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny,
100 + #IsOwnerOrReadOnly
101 + ]
102 +
103 + # url: /upload
104 + @action(methods=['POST'], detail=True, permission_classes=[AllowAny],
105 + url_path='upload', url_name='upload')
106 + def upload(self, request, pk):
107 + if request.method == 'POST':
108 + s3 = boto3.client('s3')
109 + #s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
110 + s3_bucket = 'arn:aws:s3:::[s3id]'
111 + #file_name = request.GET['image_name']
112 + file_name = request.GET.get('image_name', '')
113 + file_type = mimetypes.guess_type(file_name)[0]
114 + presigned_post = s3.generate_presigned_post(
115 + Bucket=s3_bucket,
116 + Key=file_name,
117 + Fields={"acl": "private", "Content-Type": file_type},
118 + Conditions=[
119 + {"acl": "public-read"},
120 + {"Content-Type": file_type}
121 + ],
122 + ExpiresIn=3600
123 + )
124 +
125 + data = {
126 + "signed_url": presigned_post,
127 + 'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
128 + }
129 + return presigned_post['url']
130 +
131 + # url: /status
132 + @action(methods=['POST'], detail=True, permission_classes=[AllowAny],
133 + url_path='status', url_name='status')
134 + def status(self, request):
135 + if request.method == 'POST':
136 + #name = request.POST['name']
137 + name = request.POST.get('name', '')
138 + up_time = request.POST.get('updated_time', '')
139 + try:
140 + item = Item.objects.get(name=name, updated_time=up_time)
141 + except Item.DoesNotExist:
142 + return Response({'Error': 'File Upload Error'}, status=status.HTTP_200_OK)
143 + return Response({'Message': 'File Upload Successful'}, status=status.HTTP_200_OK)
144 +
145 + """
146 + # url: /children
147 + @action(methods=['POST'], detail=True, permission_classes=[AllowAny],
148 + url_path='children', url_name='children')
149 + def children(self, request):
150 + if request.method == 'POST':
151 + #name = request.POST['name']
152 + name = request.POST.get('name', '')
153 + path = request.POST.get('path', '')
154 + parent = request.POST.get('item_id', '')
155 + daughter = Item(name = name, path = path, parent = parent)
156 +
157 + daughter.save()
158 + """
159 +
160 +
161 +"""
162 +class ItemViewSet(viewsets.ModelViewSet):
163 +
164 + #API endpoint that allows groups to be viewed or edited.
165 +
166 + queryset = Item.objects.all().order_by('-item_id')
167 + serializer_class = ItemSerializer
168 + permission_classes = [permissions.IsAuthenticated]
169 +
170 + def item_list(self, request):
171 + if request.method == 'GET':
172 + items = Item.objects.all()
173 + serializer = ItemSerializer(items, many=True)
174 + return JsonResponse(serializer.data, safe=False)
175 + elif request.method == 'POST':
176 + s3 = boto3.client('s3')
177 + s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
178 + file_name = request.GET['image_name']
179 + file_type = mimetypes.guess_type(file_name)[0]
180 + presigned_post = s3.generate_presigned_post(
181 + Bucket=s3_bucket,
182 + Key=file_name,
183 + Fields={"acl": "private", "Content-Type": file_type},
184 + Conditions=[
185 + {"acl": "public-read"},
186 + {"Content-Type": file_type}
187 + ],
188 + ExpiresIn=3600
189 + )
190 +
191 + data = {
192 + "signed_url": presigned_post,
193 + 'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
194 + }
195 + return presigned_post['url']
196 +"""
197 +
198 +
199 +
200 +"""
201 + #url: /items/{item_id}/upload
202 + @action(methods=['post'], detail=True, permission_classes=[IsAuthenticated],
203 + url_path='upload', url_name='upload')
204 + def upload(self, request):
205 + s3 = boto3.client('s3')
206 + s3_bucket = os.environ.get('AWS_STORAGE_BUCKET_NAME')
207 + file_name = request.GET['image_name']
208 + file_type = mimetypes.guess_type(file_name)[0]
209 + presigned_post = s3.generate_presigned_post(
210 + Bucket=s3_bucket,
211 + Key=file_name,
212 + Fields={"acl": "private", "Content-Type": file_type},
213 + Conditions=[
214 + {"acl": "public-read"},
215 + {"Content-Type": file_type}
216 + ],
217 + ExpiresIn=3600
218 + )
219 +
220 + data = {
221 + "signed_url": presigned_post,
222 + 'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name)
223 + }
224 + return presigned_post['url']
225 +
226 + def upload(self, request):
227 + if request.method == 'POST':
228 + serializer = ItemSerializer(data=request.data)
229 + if serializer.is_valid():
230 + BUCKET_NAME = 'presigned-post-example'
231 + KEY_NAME = 'cat.jpg'
232 +
233 + s3 = boto3.client('s3')
234 +
235 + resp = s3.generate_presigned_post(
236 + Bucket = BUCKET_NAME,
237 + Key = KEY_NAME,
238 + )
239 +
240 + resp['fields']['file'] = '@{key}'.format(key=KEY_NAME)
241 +
242 + form_values = "\n".join(["-F {key}={value} \\".format(key=key, value=value)
243 + for key, value in resp['fields'].items()])
244 +
245 + # authentication_classes = (authentication.SessionAuthentication,)
246 + # permission_classes = [IsAuthenticated, ]
247 +"""
1 -from django.contrib import admin
2 -
3 -# Register your models here.
1 -from django.contrib.auth.models import User, Group
2 -from rest_framework import viewsets
3 -from rest_framework import permissions
4 -from khudrive.api.serializers import UserSerializer,GroupSerializer
5 -
6 -
7 -class UserViewSet(viewsets.ModelViewSet):
8 - """
9 - API endpoint that allows users to be viewed or edited.
10 - """
11 - queryset = User.objects.all().order_by('-date_joined')
12 - serializer_class = UserSerializer
13 - permission_classes = [permissions.IsAuthenticated]
14 -
15 -
16 -class ItemViewSet(viewsets.ModelViewSet):
17 - """
18 - API endpoint that allows groups to be viewed or edited.
19 - """
20 - queryset = Group.objects.all()
21 - serializer_class = GroupSerializer
22 - permission_classes = [permissions.IsAuthenticated]
...\ No newline at end of file ...\ No newline at end of file
1 """ 1 """
2 Django settings for khudrive project. 2 Django settings for khudrive project.
3 3
4 -Generated by 'django-admin startproject' using Django 3.0.6. 4 +Generated by 'django-admin startproject' using Django 3.0.7.
5 5
6 For more information on this file, see 6 For more information on this file, see
7 https://docs.djangoproject.com/en/3.0/topics/settings/ 7 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__))) ...@@ -20,7 +20,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20 # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 20 # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
21 21
22 # SECURITY WARNING: keep the secret key used in production secret! 22 # SECURITY WARNING: keep the secret key used in production secret!
23 -SECRET_KEY = '3b=a99pdbz*48$9$kh@h3tkb*9w-m3vtf8ngyymdzwpl5$emwn' 23 +SECRET_KEY = ')i0_(*4t7k3=rcqp*_i0u((9zbk8q(2(3tk(%$woji-e-37=o*'
24 24
25 # SECURITY WARNING: don't run with debug turned on in production! 25 # SECURITY WARNING: don't run with debug turned on in production!
26 DEBUG = True 26 DEBUG = True
...@@ -38,7 +38,7 @@ INSTALLED_APPS = [ ...@@ -38,7 +38,7 @@ INSTALLED_APPS = [
38 'django.contrib.messages', 38 'django.contrib.messages',
39 'django.contrib.staticfiles', 39 'django.contrib.staticfiles',
40 'rest_framework', 40 'rest_framework',
41 - # 'api.apps.ApiConfig', 41 + 'api.apps.ApiConfig',
42 ] 42 ]
43 43
44 MIDDLEWARE = [ 44 MIDDLEWARE = [
...@@ -74,11 +74,18 @@ WSGI_APPLICATION = 'khudrive.wsgi.application' ...@@ -74,11 +74,18 @@ WSGI_APPLICATION = 'khudrive.wsgi.application'
74 74
75 # Database 75 # Database
76 # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 76 # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
77 -
78 DATABASES = { 77 DATABASES = {
78 + # 'default': {
79 + # 'ENGINE': 'django.db.backends.sqlite3',
80 + # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
81 + # }
79 'default': { 82 'default': {
80 - 'ENGINE': 'django.db.backends.sqlite3', 83 + 'ENGINE': 'django.db.backends.postgresql',
81 - 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 84 + 'NAME': 'khuDrive',
85 + 'USER': 'jooheekwon',
86 + 'PASSWORD': '',
87 + 'HOST': 'localhost',
88 + 'PORT': '',
82 } 89 }
83 } 90 }
84 91
......
...@@ -13,20 +13,21 @@ Including another URLconf ...@@ -13,20 +13,21 @@ Including another URLconf
13 1. Import the include() function: from django.urls import include, path 13 1. Import the include() function: from django.urls import include, path
14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 """ 15 """
16 -
17 from django.urls import include, path 16 from django.urls import include, path
18 from rest_framework import routers 17 from rest_framework import routers
19 -from khudrive.api import views
20 from django.contrib import admin 18 from django.contrib import admin
19 +from api import views
20 +from django.conf.urls import url
21 21
22 router = routers.DefaultRouter() 22 router = routers.DefaultRouter()
23 router.register(r'users', views.UserViewSet) 23 router.register(r'users', views.UserViewSet)
24 -router.register(r'groups', views.ItemViewSet) 24 +router.register(r'items', views.ItemViewSet)
25 25
26 # Wire up our API using automatic URL routing. 26 # Wire up our API using automatic URL routing.
27 # Additionally, we include login URLs for the browsable API. 27 # Additionally, we include login URLs for the browsable API.
28 urlpatterns = [ 28 urlpatterns = [
29 path('admin/', admin.site.urls), 29 path('admin/', admin.site.urls),
30 path('', include(router.urls)), 30 path('', include(router.urls)),
31 - path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) 31 + url(r'^upload/$', views.ItemViewSet.upload, name='upload'),
32 + url(r'^status/$', views.ItemViewSet.status, name='status'),
32 ] 33 ]
......