diff options
Diffstat (limited to 'app/backend.py')
-rw-r--r-- | app/backend.py | 56 |
1 files changed, 33 insertions, 23 deletions
diff --git a/app/backend.py b/app/backend.py index 6c59edd..0dbebb8 100644 --- a/app/backend.py +++ b/app/backend.py @@ -2,38 +2,48 @@ import os import magic +from functools import partial class Storage: - def __init__(self, root_path): - self.root = root_path + def __init__(self, path_rel, path_app): + self.path = path_app + self.root = path_rel def _join(self, *arg): - return os.path.join(self.root, *arg) + return os.path.join(self.path, *arg) - def get_file(self, module, year, name): - with open(self._join(module, year, name), 'r') as f: - data = f.read() - mime = magic.Magic(mime=True) - mime_type = mime.from_buffer(data[:1024]) - return mime_type, data + def get_courses(self): + """ Lists all courses of a study """ + return [o.decode('utf-8') for o in os.listdir(self.path) + if os.path.isdir(self._join(o))] - def get_modules(self): - return [o for o in os.listdir(self.root) if os.path.isdir(self._join(o))] + def exam_exists(self, course, year, name): + """ Exists if an exam (file) exists """ + return os.path.exists(self._join(course, year, name)) - def get_module(self, module): - for root, dirs, files in os.walk(self._join(module)): + def add_exam(self, course, year, filename, data): + # create course dir with year if it does not exist already + dir_name = self._join(course, year) + if not os.path.exists(dir_name): + os.makedirs(dir_name) + + # save exam + path = self._join(course, year, filename) + with open(path, 'wb') as f: + f.write(data) + + def get_exams(self, name): + """ Lists all exams of a given course """ + # loop over all directories which do not contain any subdirs + for root, dirs, files in os.walk(self._join(name)): if len(dirs) == 0: + # metainformation is encoded in path: course/year/exam.pdf splitted = root.split(os.path.sep) if len(splitted) > 1: year = splitted[-1] - module = splitted[-2] + course = splitted[-2] if year.isdigit(): - yield (year, files) - - def add_file(self, module, year, filename, data): - dir_name = self._join(module, year) - if not os.path.exists(dir_name): - os.makedirs(dir_name) - path = self._join(module, year, filename) - with open(path, 'wb') as f: - f.write(data) + # yield entries as tuples (name, path) grouped by years + func = partial(os.path.join, self.root, course, year) + entries = [(f, func(f)) for f in files] + yield (year, entries) |