Coverage for app/logic/fileHandler.py: 81%
54 statements
« prev ^ index » next coverage.py v7.2.5, created at 2023-05-24 14:13 +0000
« prev ^ index » next coverage.py v7.2.5, created at 2023-05-24 14:13 +0000
1import os
2from flask import redirect, url_for
3from app import app
4from app.models.attachmentUpload import AttachmentUpload
6class FileHandler:
7 def __init__(self,files=None, courseId=None, eventId=None):
8 self.files=files
9 self.path = app.config['files']['base_path']
10 self.courseId = courseId
11 self.eventId = eventId
12 if courseId:
13 self.path = os.path.join(self.path, app.config['files']['course_attachment_path'], str(courseId))
14 elif eventId:
15 self.path = os.path.join(self.path, app.config['files']['event_attachment_path'], str(eventId))
16 try:
17 os.makedirs(self.path)
18 except:
19 print("Directory exists.")
21 def getFileFullPath(self, newfile = None):
22 """
23 This creates the directory/path for the object from the "Choose File" input in the create event and edit event.
24 :returns: directory path for attachment
25 """
26 try:
27 # tries to create the full path of the files location and passes if
28 # the directories already exist or there is no attachment
29 filePath=(os.path.join(self.path, newfile.filename))
30 except AttributeError: # will pass if there is no attachment to save
31 pass
32 except FileExistsError:
33 pass
34 return filePath
36 def saveFiles(self):
37 """ Saves the attachment in the app/static/files/eventattachments/ or courseattachements/ directory """
38 try:
39 for file in self.files:
40 if self.eventId:
41 isFileInEvent = AttachmentUpload.select().where(AttachmentUpload.event == self.eventId, AttachmentUpload.fileName == file.filename).exists()
42 if not isFileInEvent:
43 AttachmentUpload.create(event = self.eventId, fileName = file.filename)
44 file.save(self.getFileFullPath(newfile = file)) # saves attachment in directory
45 elif self.courseId:
46 isFileInCourse = AttachmentUpload.select().where(AttachmentUpload.course == self.courseId, AttachmentUpload.fileName == file.filename).exists()
47 if not isFileInCourse:
48 AttachmentUpload.create(course = self.courseId, fileName = file.filename)
49 file.save(self.getFileFullPath(newfile = file)) # saves attachment in directory
50 except AttributeError: # will pass if there is no attachment to save
51 pass
53 def retrievePath(self,files):
54 pathDict={}
55 for file in files:
56 pathDict[file.fileName] = ((self.path+"/"+ file.fileName)[3:], file)
58 return pathDict
60 def deleteFile(self, fileId):
61 """
62 Deletes attachmant from the app/static/files/eventattachments/ or courseattachments/ directory
63 """
64 try:
65 file = AttachmentUpload.get_by_id(fileId)
66 path = os.path.join(self.path, file.fileName)
67 os.remove(path)
68 file.delete_instance()
69 except AttributeError: #passes if no attachment is selected.
70 pass