권주희

implement search API by keyword

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 3 +from api.models import Item, SharedItem
4 4
5 5
6 class UserSerializer(serializers.HyperlinkedModelSerializer): 6 class UserSerializer(serializers.HyperlinkedModelSerializer):
...@@ -17,3 +17,8 @@ class ItemSerializer(serializers.ModelSerializer): ...@@ -17,3 +17,8 @@ class ItemSerializer(serializers.ModelSerializer):
17 class Meta: 17 class Meta:
18 model = Item 18 model = Item
19 fields = '__all__' 19 fields = '__all__'
20 +
21 +class SharedItemSerializer(serializers.ModelSerializer):
22 + class Meta:
23 + model = Item
24 + fields = '__all__'
......
1 import mimetypes 1 import mimetypes
2 +import json
2 import os 3 import os
3 import boto3 4 import boto3
4 5
5 -from django.contrib.auth.models import User, Group 6 +from django.contrib.auth.models import User
7 +from django.core import serializers
6 from django.http import HttpResponse, JsonResponse 8 from django.http import HttpResponse, JsonResponse
7 from rest_framework import viewsets 9 from rest_framework import viewsets
8 from rest_framework import permissions 10 from rest_framework import permissions
...@@ -14,10 +16,10 @@ from rest_framework.decorators import action ...@@ -14,10 +16,10 @@ from rest_framework.decorators import action
14 from rest_framework.parsers import JSONParser 16 from rest_framework.parsers import JSONParser
15 from rest_framework.permissions import IsAuthenticated, AllowAny 17 from rest_framework.permissions import IsAuthenticated, AllowAny
16 18
17 -from api.models import Item 19 +from api.models import Item, SharedItem
18 from api.serializers import UserSerializer,GroupSerializer,ItemSerializer 20 from api.serializers import UserSerializer,GroupSerializer,ItemSerializer
19 from rest_framework import generics 21 from rest_framework import generics
20 - 22 +from rest_framework import status
21 23
22 class UserViewSet(viewsets.ModelViewSet): 24 class UserViewSet(viewsets.ModelViewSet):
23 """ 25 """
...@@ -27,70 +29,6 @@ class UserViewSet(viewsets.ModelViewSet): ...@@ -27,70 +29,6 @@ class UserViewSet(viewsets.ModelViewSet):
27 serializer_class = UserSerializer 29 serializer_class = UserSerializer
28 permission_classes = [permissions.IsAuthenticated] 30 permission_classes = [permissions.IsAuthenticated]
29 31
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 32
95 class ItemViewSet(viewsets.ModelViewSet): 33 class ItemViewSet(viewsets.ModelViewSet):
96 34
...@@ -99,10 +37,9 @@ class ItemViewSet(viewsets.ModelViewSet): ...@@ -99,10 +37,9 @@ class ItemViewSet(viewsets.ModelViewSet):
99 permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, 37 permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny,
100 #IsOwnerOrReadOnly 38 #IsOwnerOrReadOnly
101 ] 39 ]
102 -
103 # url: /upload 40 # url: /upload
104 @action(methods=['POST'], detail=True, permission_classes=[AllowAny], 41 @action(methods=['POST'], detail=True, permission_classes=[AllowAny],
105 - url_path='upload', url_name='upload') 42 + url_path='upload', url_name='upload')
106 def upload(self, request, pk): 43 def upload(self, request, pk):
107 if request.method == 'POST': 44 if request.method == 'POST':
108 s3 = boto3.client('s3') 45 s3 = boto3.client('s3')
...@@ -142,106 +79,14 @@ class ItemViewSet(viewsets.ModelViewSet): ...@@ -142,106 +79,14 @@ class ItemViewSet(viewsets.ModelViewSet):
142 return Response({'Error': 'File Upload Error'}, status=status.HTTP_200_OK) 79 return Response({'Error': 'File Upload Error'}, status=status.HTTP_200_OK)
143 return Response({'Message': 'File Upload Successful'}, status=status.HTTP_200_OK) 80 return Response({'Message': 'File Upload Successful'}, status=status.HTTP_200_OK)
144 81
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 82
157 - daughter.save() 83 + # url: items/search
158 - """ 84 + @action(methods=['GET'], detail=False, permission_classes=[AllowAny], url_path='search', url_name='search')
159 - 85 + def search(self, request):
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': 86 if request.method == 'GET':
172 - items = Item.objects.all() 87 + keyword = request.GET.get('keyword', '')
173 - serializer = ItemSerializer(items, many=True) 88 + item_list = Item.objects.filter(name__icontains = keyword)
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 89
242 - form_values = "\n".join(["-F {key}={value} \\".format(key=key, value=value) 90 + data = serializers.serialize("json", item_list)
243 - for key, value in resp['fields'].items()]) 91 + return Response({'data': {'list' : data}}, status=status.HTTP_200_OK)
244 92
245 - # authentication_classes = (authentication.SessionAuthentication,)
246 - # permission_classes = [IsAuthenticated, ]
247 -"""
......
...@@ -30,4 +30,6 @@ urlpatterns = [ ...@@ -30,4 +30,6 @@ urlpatterns = [
30 path('', include(router.urls)), 30 path('', include(router.urls)),
31 url(r'^upload/$', views.ItemViewSet.upload, name='upload'), 31 url(r'^upload/$', views.ItemViewSet.upload, name='upload'),
32 url(r'^status/$', views.ItemViewSet.status, name='status'), 32 url(r'^status/$', views.ItemViewSet.status, name='status'),
33 + url(r'^search/$', views.ItemViewSet.search, name='search'),
34 +
33 ] 35 ]
......