def post(self, request): # Get the post request and extract the IDs of the temporary upload(s) # to be permanently stored. data = request.POST try: filepond_ids = data.getlist('filepond') except KeyError: LOG.error('No filepond key found in submitted form.') return HttpResponseBadRequest('Missing filepond key in form.') if not isinstance(filepond_ids, list): LOG.error('Unexpected data type in form.') return HttpResponseBadRequest('Unexpected data type in form.') # Go through the list of IDs. For each, look up the associated temp # upload and call django-drf-filepond's API function store_upload. # This stores the file to a local or remote file store depending on # how the library is configured. stored_uploads = [] for upload_id in filepond_ids: tu = TemporaryUpload.objects.get(upload_id=upload_id) LOG.debug('Storing upload: [%s]' % filepond_ids) store_upload(upload_id, os.path.join(upload_id, tu.upload_name)) stored_uploads.append(upload_id) # Return the list of uploads that were stored. return HttpResponse(json.dumps({ 'status': 'OK', 'uploads': stored_uploads }), content_type='application/json')
def test_store_upload_unset_file_store_path(self): fsp = local_settings.FILE_STORE_PATH local_settings.FILE_STORE_PATH = None with self.assertRaisesMessage( ImproperlyConfigured, 'A required setting is missing in ' 'your application configuration.'): store_upload('hsdfiuysh78sdhiu', '/test_storage/test_file.txt') local_settings.FILE_STORE_PATH = fsp
def portfolio_create(request): # Vue랑 연결했을때 이상하면 수정 필수. ### 에러 작성 했을때 에러 뜨면 그때가서 바꿔주기..... demorequest = request.data # print(demorequest) user = get_object_or_404(User, pk=request.data.get('user')) for i, image in enumerate(demorequest['images']): # print(image) # if TemporaryUpload.objects.filter(upload_id=image).exists(): tu = get_object_or_404(TemporaryUpload, upload_id=image) # print(tu) su = store_upload(tu.upload_id, destination_file_path=f'{user}/{str(tu.file_id)+tu.upload_name}') tu.delete() # http://i02b102.p.ssafy.io:8054/media/ url = 'http://i02b102.p.ssafy.io:8054/media/' + str(su.file_path) demorequest[f'content_img_{i+1}'] = url for idx, content in enumerate(demorequest['contents']): demorequest[f'content_sub_{idx+1}'] = content serializer = PortfolioCreateSerializer(data=demorequest) # print(request) if serializer.is_valid(raise_exception=True): serializer.save() # print(serializer.data) return Response(serializer.data)
def test_store_upload_path_with_dirname_no_leading_sep(self): test_target_dirname = self.test_target_dirname if not test_target_dirname.startswith(os.sep): test_target_dirname = os.sep + test_target_dirname su = store_upload(self.upload_id, test_target_dirname) upload_id = su.upload_id # File should be stored relative to the file store path so the # leading os.sep should be ignored. su = StoredUpload.objects.get(upload_id=upload_id) target_file_path = os.path.join(test_target_dirname, self.fn) if target_file_path.startswith(os.sep): target_file_path = target_file_path[1:] LOG.debug('About to check that file path <%s> and stored path <%s> ' 'are equal' % (target_file_path, su.file.name)) self.assertEqual( target_file_path, su.file.name, 'File has been stored with wrong filename in the database.') # Check that the file has actually been stored in the correct # location and that the temporary file has been deleted upload_tmp_base = getattr(local_settings, 'UPLOAD_TMP', None) file_store_path = getattr(local_settings, 'FILE_STORE_PATH', None) if not file_store_path: raise ValueError('Couldn\'t access file store path') file_full_path = os.path.join(file_store_path, su.file.name) self.assertTrue(os.path.exists(file_full_path) and os.path.isfile(file_full_path)) self.assertFalse(os.path.exists( os.path.join(upload_tmp_base, self.upload_id, self.file_id)))
def competition_create(request): demorequest = request.data user = get_object_or_404(User, pk=request.data.get('user_name')) # demorequest['user_name'] = 1 # user = '******' tech_list = [] for tech in request.data.get('tech_category'): te = get_object_or_404(Tech, tech_stack=tech) tech_list.append(te.id) # print(demorequest) # print(user) filepond = get_object_or_404(TemporaryUpload, upload_id=request.data.get('recruit_logo')) if not os.path.exists( f'./media/{user}'): #str(os.getcwd())+f'\media\{user}' os.makedirs(f'.\media\{user}') su = store_upload(filepond.upload_id, destination_file_path= f'{user}/{str(filepond.file_id)+filepond.upload_name}') filepond.delete() #http://i02b102.p.ssafy.io:8054/ http://192.168.31.126:8000/ url = 'http://i02b102.p.ssafy.io:8054/media/' + str(su.file_path) demorequest['recruit_logo'] = url demorequest['tech_category'] = tech_list serializer = CompetitionCreateSerializer(data=demorequest) # print(serializer) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) return Response(status=400)
def user_update(request, id): user = get_object_or_404(User, pk=id) # tech = Tech.objects.all() if request.method == 'POST': demo = request.data if request.data.get('profile_img'): filepond = get_object_or_404( TemporaryUpload, upload_id=request.data.get('profile_img')) if not os.path.exists(f'./media/{user}'): os.makedirs(f'./media/{user}') su = store_upload( filepond.upload_id, destination_file_path= f'{user}/{str(filepond.file_id)+filepond.upload_name}') filepond.delete() # url = 'http://i02b102.p.ssafy.io:8054/media/'+str(filepond.file) url = 'http://i02b102.p.ssafy.io:8054/media/' + str(su.file_path) demo['profile_img'] = url serializer = UserUpdateSerializer(data=demo, instance=user) # print('serializer', serializer) if serializer.is_valid(raise_exception=True): # print('request.data: ', request.data) serializer.save() return Response(serializer.data) elif request.method == 'DELETE': user.delete() return Response({'message': 'deleted!'})
def portfolio_delete_update(request, portfolio_pk): portfolio = get_object_or_404(Portfolio, pk=portfolio_pk) if request.method == 'PUT': demorequest = request.data user = get_object_or_404(User, pk=portfolio.user.id) if demorequest.get('images'): for i, image in enumerate(demorequest['images']): # print(image) if TemporaryUpload.objects.filter(upload_id=image).exists(): tu = get_object_or_404(TemporaryUpload, upload_id=image) # print(tu) su = store_upload(tu.upload_id, destination_file_path=f'{user}/{str(tu.file_id)+tu.upload_name}') tu.delete() # http://i02b102.p.ssafy.io:8054/media/ url = 'http://i02b102.p.ssafy.io:8054/media/' + str(su.file_path) demorequest[f'content_img_{i+1}'] = url if demorequest.get('contents'): for idx, content in enumerate(demorequest['contents']): demorequest[f'content_sub_{idx+1}'] = content if not demorequest.get('title'): demorequest['title'] = portfolio.title demorequest['user'] = portfolio.user.id serializer = PortfolioCreateSerializer(data=demorequest, instance=portfolio) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) else: portfolio.delete() return Response({'message':'deleted!'})
def test_store_multiple_uploads_to_same_dir(self): test_target_filename = self.test_target_filename test_target_filename2 = self.test_target_filename2 if test_target_filename.startswith(os.sep): test_target_filename = test_target_filename[1:] if test_target_filename2.startswith(os.sep): test_target_filename2 = test_target_filename2[1:] su = store_upload(self.upload_id, test_target_filename) su2 = store_upload(self.upload_id2, test_target_filename2) self.assertEqual( test_target_filename, su.file_path, 'File has been stored with wrong filename in the database.') self.assertEqual( test_target_filename2, su2.file_path, 'File 2 has been stored with wrong filename in the database.') # Check that the files have actually been stored in the correct # locations and that the temporary files have been deleted upload_tmp_base = getattr(local_settings, 'UPLOAD_TMP', None) file_store_path = getattr(local_settings, 'FILE_STORE_PATH', None) if not file_store_path: raise ValueError('Couldn\'t access file store path') file_full_path = os.path.join(file_store_path, su.file_path) file_full_path2 = os.path.join(file_store_path, su2.file_path) # Check first file self.assertTrue( os.path.exists(file_full_path) and os.path.isfile(file_full_path)) self.assertFalse( os.path.exists( os.path.join(upload_tmp_base, self.upload_id, self.file_id))) # Check second file self.assertTrue( os.path.exists(file_full_path2) and os.path.isfile(file_full_path2)) self.assertFalse( os.path.exists( os.path.join(upload_tmp_base, self.upload_id2, self.file_id)))
def post(self, request, *args, **kwargs): project_id = self.kwargs['project_id'] upload_ids = request.data.pop('uploadIds') format = request.data.pop('format') tus = [TemporaryUpload.objects.get(upload_id=upload_id) for upload_id in upload_ids] sus = [ store_upload( tu.upload_id, destination_file_path=os.path.join(tu.file.name, tu.upload_name) ) for tu in tus ] filenames = [su.file.path for su in sus] task = ingest_data.delay( user_id=request.user.id, project_id=project_id, filenames=filenames, format=format, **request.data ) return Response({'task_id': task.task_id})
def user_signup(request): # print('request: ', request.data) demo = request.data filepond = get_object_or_404(TemporaryUpload, upload_id=request.data.get('verified_img')) #username if not os.path.exists(f'./media/{filepond.upload_id}'): os.makedirs(f'./media/{filepond.upload_id}') su = store_upload( filepond.upload_id, destination_file_path=f'{filepond.upload_id}/{filepond.upload_name}') filepond.delete() # url = 'http://i02b102.p.ssafy.io:8054/media/'+str(su.file_path) url = 'http://i02b102.p.ssafy.io:8054/media/' + str(su.file_path) demo['verified_img'] = url serializer = UserCreationSerializer(data=demo) # filepond.delete() if serializer.is_valid(raise_exception=True): user = serializer.save() user.set_password(request.data.get('password')) user.save() return Response({'message': '회원가입이 성공적으로 완료되었습니다.'})
def test_store_upload_path_with_filename(self): test_target_filename = self.test_target_filename if test_target_filename.startswith(os.sep): test_target_filename = test_target_filename[1:] su = store_upload(self.upload_id, test_target_filename) upload_id = su.upload_id su = StoredUpload.objects.get(upload_id=upload_id) self.assertEqual( test_target_filename, su.file_path, 'File has ' 'been stored with wrong filename in the database.') # Check that the file has actually been stored in the correct # location and that the temporary file has been deleted upload_tmp_base = getattr(local_settings, 'UPLOAD_TMP', None) file_store_path = getattr(local_settings, 'FILE_STORE_PATH', None) if not file_store_path: raise ValueError('Couldn\'t access file store path') file_full_path = os.path.join(file_store_path, su.file_path) self.assertTrue( os.path.exists(file_full_path) and os.path.isfile(file_full_path)) self.assertFalse( os.path.exists( os.path.join(upload_tmp_base, self.upload_id, self.file_id)))
def test_store_upload_with_root_path(self): test_target_dirname = '/' su = store_upload(self.upload_id, test_target_dirname) upload_id = su.upload_id su = StoredUpload.objects.get(upload_id=upload_id) target_file_path = os.path.join(test_target_dirname, self.fn) LOG.debug('About to check that file path <%s> and stored path <%s> ' 'are equal' % (target_file_path, su.file_path)) self.assertEqual( target_file_path[1:], su.file_path, 'File has been stored with wrong filename in the database.') # Check that the file has actually been stored in the correct # location and that the temporary file has been deleted upload_tmp_base = getattr(local_settings, 'UPLOAD_TMP', None) file_store_path = getattr(local_settings, 'FILE_STORE_PATH', None) if not file_store_path: raise ValueError('Couldn\'t access file store path') file_full_path = os.path.join(file_store_path, su.file_path) self.assertTrue( os.path.exists(file_full_path) and os.path.isfile(file_full_path)) self.assertFalse( os.path.exists( os.path.join(upload_tmp_base, self.upload_id, self.file_id)))
def competition_delete_update(request, competition_pk): competition = get_object_or_404(Competition, pk=competition_pk) demo = request.data if request.method == 'PUT': user = get_object_or_404(User, pk=request.data.get('user_name')) if request.data.get('tech_category'): if not request.data.get('tech_category')[0].isdecimal(): tech_list = [] for tech in request.data.get('tech_category'): te = get_object_or_404(Tech, tech_stack=tech) tech_list.append(te.id) demo['tech_category'] = tech_list if len(request.data.get('recruit_logo')) < 23: filepond = get_object_or_404( TemporaryUpload, upload_id=request.data.get('recruit_logo')) su = store_upload( filepond.upload_id, destination_file_path= f'{user}/{str(filepond.file_id)+filepond.upload_name}') filepond.delete() url = 'http://i02b102.p.ssafy.io:8054/media/' + str(su.file_path) demo['recruit_logo'] = url # print(demo) serializer = CompetitionCreateSerializer(data=demo, instance=competition) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400) # return Response({'message':'updated competition!!!'}) else: competition.delete() return Response(status=204)
def test_store_upload_path_blank(self): with self.assertRaisesMessage(ValueError, 'No destination file ' 'path provided.'): store_upload('hsdfiuysh78sdhiuf73gds', '')
def upload_to_store(temporary_uploads): for tu in temporary_uploads: store_upload(tu.upload_id, destination_file_path=tu.file.name)
def test_store_upload_invalid_id(self): with self.assertRaisesMessage(ValueError, 'The provided upload ID ' 'is of an invalid format.'): store_upload('hsdfiuysh78sdhiu', '/test_storage/test_file.txt')
def test_store_upload_invalid_id_correct_format(self): with self.assertRaisesMessage(ValueError, 'Record for the specified ' 'upload_id doesn\'t exist'): store_upload('hsdfiuysh78sdhiuf73gds', '/test_storage/test.txt')