def test_api_list_user_files(user_with_files, client, jwt_headers): """ Полный список загруженных юзером файлов (без фильтрации). """ response = client.get(reverse('v2:file-list'), **jwt_headers) assert response.status_code == status.HTTP_200_OK data = response.json()['results'] assert len(data) == user_with_files.files.is_uploaded().count() serializer = FileSerializer(data=data, many=True) assert serializer.is_valid()
def test_api_retrieve_some_files(client, test_user): """ Получение матаданных файла. """ file_uuid = test_user.files.first().uuid response = client.get(reverse('v2:file-detail', kwargs={'uuid': file_uuid})) assert response.status_code == status.HTTP_200_OK data = response.json() serializer = FileSerializer(data=data) assert serializer.is_valid()
def test_api_some_file_upload(sample_file, client, jwt_token, settings): """ Загруза тестового файла на сервер. """ settings.DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' response = client.post(reverse('v2:file-upload'), data={'file': sample_file}, format='multipart', HTTP_AUTHORIZATION=f'Bearer {jwt_token}') assert response.status_code == status.HTTP_201_CREATED data = response.json() serializer = FileSerializer(data=response.data) assert serializer.is_valid() assert serializer.data['type'] == 'document' assert serializer.data['url'].endswith(data['uuid'])
def test_api_file_upload_force_type(sample_file, client, jwt_token, settings): """ Форсим тип загружаймого файла через query params. """ settings.DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' q = QueryDict('', mutable=True) q['type'] = 'image' response = client.post(reverse('v2:file-upload') + f'?{q.urlencode()}', data={'file': sample_file}, format='multipart', HTTP_AUTHORIZATION=f'Bearer {jwt_token}') assert response.status_code == status.HTTP_201_CREATED data = response.json() serializer = FileSerializer(data=data) assert serializer.is_valid() assert serializer.data['type'] == 'image' assert serializer.data['url'].endswith(data['uuid'])
def get(self, request): try: # Permission 확인 if not is_token_valid(token=request.headers['ID-Token'], user_id=request.data['user_id']): return Response(status=status.HTTP_403_FORBIDDEN) res = [] user_id = request.GET['userId'] group_name = request.GET['groupName'] groups = GroupInfo.objects.values('group_id').distinct().filter( display_name__contains=group_name, user_id=user_id) for group_id in groups: group_id = group_id['group_id'] files = FaceInfo.objects.values('file_id').distinct().filter( group_id=group_id, user_id=user_id) for file in files: file_id = file['file_id'] item = File.objects.get(file_id=file_id, user_id=user_id) res.append(item) serializer = FileSerializer(res, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: msg = {'msg': str(e)} print(e) return Response(msg, status=status.HTTP_400_BAD_REQUEST)
def api_detail_file(request, id_): try: file = ControlFile.objects.get(id=id_) except ControlFile.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if not file: return Response(status=status.HTTP_404_NOT_FOUND) serializer = FileSerializer(file) return Response(serializer.data)
def file_list(request): if request.method == 'GET': files = Files.objects.all() title = request.GET.get('title', None) if title is not None: files = files.filter(title__icontains=title) files_serializer = FileSerializer(files, many=True) return JsonResponse(files_serializer.data, safe=False) # 'safe=False' for objects serialization elif request.method == 'POST': file_data = JSONParser().parse(request) file_serializer = FileSerializer(data=file_data) if file_serializer.is_valid(): file_serializer.save() return JsonResponse(file_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': count = Files.objects.all().delete() return JsonResponse( { 'message': '{} Files were deleted successfully!'.format( count[0]) }, status=status.HTTP_204_NO_CONTENT)
class ReviewSerializer(serializers.ModelSerializer): images = FileSerializer(many=True, read_only=True) created_by = serializers.SerializerMethodField('get_user') def get_user(self, obj): return { 'first_name': obj.created_by.first_name, 'last_name': obj.created_by.last_name, 'email': obj.created_by.email, } class Meta: model = Review fields = '__all__'
def get(self, request, format=None): try: # Permission 확인 if not is_token_valid(token=request.headers['ID-Token'], user_id=request.data['user_id']): return Response(status=status.HTTP_403_FORBIDDEN) keyword = request.GET['keyword'] userId = request.GET['userId'] res = File.objects.filter( name__contains=keyword, user_id=userId ) serializer = FileSerializer(res, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: msg = {'error': str(e)} # print(e) return Response(msg, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, folder_id): # Permission 확인 if not is_token_valid(token=request.headers['ID-Token'], user_id=request.GET['user_id']): return Response(status=status.HTTP_403_FORBIDDEN) # 1. 폴더 목록 조회 folders = Folder.objects.filter(parent_id=folder_id) folder_serializers = FolderSerializer(folders, many=True) # 2. 파일 목록 조회 files = File.objects.filter(folder_id=folder_id) files_serializers = FileSerializer(files, many=True) # 3. 결과 응답 return Response( { 'folders': folder_serializers.data, 'files': files_serializers.data, }, content_type="application/json", status=status.HTTP_202_ACCEPTED)
def file_detail(request, pk): try: file = Files.objects.get(pk=pk) except Files.DoesNotExist: return JsonResponse({'message': 'The file does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': file_serializer = FileSerializer(file) return JsonResponse(file_serializer.data) elif request.method == 'PUT': file_data = JSONParser().parse(request) file_serializer = FileSerializer(file, data=file_data) if file_serializer.is_valid(): file_serializer.save() return JsonResponse(file_serializer.data) return JsonResponse(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': file.delete() return JsonResponse({'message': 'File was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)
def post(self, request, *args, **kwargs): serializer = FileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_portfolio(self, obj): qs = obj.files.filter(file_type=File.Type.PORTFOLIO, is_uploaded=True) serializers = FileSerializer(qs, many=True) return serializers.data
def file_list_published(request): files = Files.objects.filter(published=True) if request.method == 'GET': files_serializer = FileSerializer(files, many=True) return JsonResponse(files_serializer.data, safe=False)