# -*- coding: utf-8 -*- import os import magic from functools import partial class Storage: def __init__(self, path_rel, path_app): self.path = path_app self.root = path_rel def _join(self, *arg): return os.path.join(self.path, *arg) 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 exam_exists(self, course, year, name): """ Exists if an exam (file) exists """ return os.path.exists(self._join(course, year, name)) 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).encode('utf-8')): 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] course = splitted[-2] if year.isdigit(): # 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)