def read(uid: str) -> (Poll, File): """ Return poll and linked file entity by uid. """ poll = PollStore().read(uid) file = FileStore().get(poll.image_id) return (poll, file)
def download(uid: str): """ Return downloadable file object. """ file = FileStore().read(uid) if file is not None: return send_from_directory(file.path, file.name) else: abort(404)
def remove_file(filedata: dict) -> None: """ Remove file according to filedata (temporary file or stored on server). """ if filedata['uploaded']: # uploaded file should be removed infopath = os.path.join(TEMPORARY_PATH, filedata['name']) with open(infopath, 'r') as file: fileinfo = json.loads(file.read()) os.remove(infopath) os.remove(os.path.join( TEMPORARY_PATH, fileinfo['subfolder'], fileinfo['name'])) else: # file on server should be removed file = FileStore().delete(filedata['uid']) os.remove(os.path.join(file.path, file.name))
def save_files(self, limit: int) -> list: """ Synchronize with moving temporary files or removing stored files (if limit less zero then unlimited). """ result = [] for filename, filedata in json.loads(self.files.data).items(): if filedata['removed'] or limit == 0: # file should be removed remove_file(filedata) elif limit != 0: if filedata['uploaded']: # file should be stored result += [store_file(filedata, DATABASE_FILES_PATH)] else: # file should be present on server result += [FileStore().read(filedata['uid'])] limit -= 1 return result
def __init__(self, uid: str = None) -> "PollForm": """ Initiate object with values fron request. """ super(PollForm, self).__init__('pollForm') if request.method == 'GET': if uid is not None: poll = PollStore().read(uid) if poll is None: abort(404) self.title.data = poll.title self.description.data = poll.description file = FileStore().get(poll.image_id) if file is not None: self.init_files([file]) elif request.method == 'POST': self.form_valid = True if self.title.data is None: self.title.errors = ['Value required'] self.form_valid = False
def store_file(filedata: dict, target: str) -> File: """ Move temporary file to target with all subfolders, create and return File object. """ # Read data from fileinfo with open(os.path.join(TEMPORARY_PATH, filedata['name']), 'r') as file: fileinfo = json.loads(file.read()) temporary_path = os.path.join(TEMPORARY_PATH, fileinfo['subfolder']) target_path = os.path.join(target, fileinfo['subfolder']) # Move file with subfolder structure, create and return File object make_dirs(target_path) os.rename( os.path.join(temporary_path, fileinfo['name']), os.path.join(target_path, fileinfo['name']) ) os.remove(os.path.join(TEMPORARY_PATH, fileinfo['name'])) return FileStore().create( title=fileinfo['title'], name=fileinfo['name'], type=fileinfo['type'], path=target_path, size=fileinfo['size'] )