示例#1
0
 def post(self, request, format=None):
     parent = get_object_or_404(Folder, pk=request.data['parent'])
     folder = Folder(name=request.data['name'], parent=parent)
     path = self.getAvailablePath(folder)
     folder.save()
     os.mkdir(path)
     serializer = FolderSerializer(folder, many=False)
     return Response(serializer.data)
示例#2
0
文件: helper.py 项目: qyb/sohu
def get_or_create_folder_by_name(user_id, name):
    if name:
        folder = get_folder_by_name(user_id, name)
        if folder is None:
            folder = Folder()
            folder.name = name
            folder.save()
    else:
        folder = None
    
    return folder
示例#3
0
def get_or_create_folder_by_name(user_id, name):
    if name:
        folder = get_folder_by_name(user_id, name)
        if folder is None:
            folder = Folder()
            folder.name = name
            folder.save()
    else:
        folder = None

    return folder
示例#4
0
文件: utils.py 项目: ikicic/skoljka
def prepare_folder_menu(folders, user):
    """
        Given list of folders, prepare folder menu showing all those folders
        at once. Ignores from input all folder inaccessible for the given user.

        Returns dict with following keys:
            folder_children - dictionary {folder.id: list of children instances}
            folder_tree - HTML of folder tree
    """
    # Note: This method calls Folder.many_get_user_stats, which makes it
    # sometimes very slow. Actually, the method is relatively fast. Still, more
    # optimizations are welcome here, because this method is called on almost
    # every request...

    data = get_visible_folder_tree(folders, user)

    if not data:
        return {'folder_children': {}, 'folder_tree': u''}

    ancestor_ids = data['ancestor_ids']
    folder_children = data['folder_children']
    sorted_folders = data['sorted_folders']

    # Get user's solution statuses.
    user_stats = Folder.many_get_user_stats(sorted_folders, user)

    # Finally, generate menu HTML
    menu = [x._html_menu_item(x.id in ancestor_ids, x._depth,
        user_stats.get(x.id)) for x in sorted_folders]

    return {
        'folder_children': folder_children,
        'folder_tree': u''.join(menu),
#        'sorted_folders': sorted_folders, # Not used currently. Enable if needed.
    }
示例#5
0
 def form_valid(self, form):
     node = model_to_dict(form.save(commit=False), exclude=TREEBEARD_EXCLUDE)
     node["teacher"] = self.user.get_profile().teacher
     if "folderid" not in self.kwargs:
         # Root node for user
         self.object = Folder.add_root(**node)
     else:
         parent = get_object_or_404(Folder, pk=self.kwargs["folderid"])
         self.object = parent.add_child(**node)
     return HttpResponseRedirect(self.get_success_url())
示例#6
0
def add_sample_folders():
    path = os.path.join(BASE_DIR, 'folder/files/sample_folders.txt')
    folder_stack = [Folder.objects.get(parent=None)]
    with open(path) as input_file:
        added_folders = 0
        for line in input_file:
            line = line.replace('\n', '')
            name = line.lstrip(' ')
            if name == '':
                continue

            leading_spaces = len(line) - len(name)
            while leading_spaces != len(folder_stack) - 1:
                folder_stack.pop()

            formatted_name = convert_pretty_to_folder_name(name)
            folder = Folder(parent=folder_stack[-1],
                            pretty_name=name,
                            folder_name=formatted_name,
                            created_by=None)
            folder.save()
            folder_stack.append(folder)
            added_folders += 1
示例#7
0
 def get_queryset(self):
     self.getuser()
     return Folder.get_root_nodes().filter(teacher=self.user.get_profile().teacher)
示例#8
0
文件: views.py 项目: ikicic/skoljka
def _create_folders(author, parent, structure, p):
    vars = {'p': p}

    level, separator, rest = structure.partition('|')
    rest = rest.strip()

    # Split the level description into lines, remove trailing and leading
    # whitespaces, and remove empty lines
    lines = filter(None, [x.strip() for x in level.strip().split('\n')])

    # Child format defined in the first line
    # Format: var_name1/var_name2/.../var_nameN
    var_names = [x.strip() for x in lines[0].split('/')]

    # Evaluate variables in specified order, don't shuffle them!
    var_formats = []

    # List of children tuples
    children = []

    # Skip first line!
    for x in lines[1:]:
        left, separator, right = x.partition('=')

        if separator:
            # Variable definition: var_name=this is a example number {x}
            var_formats.append((left, right))
        elif left[0] == '%':
            # Special command
            if left.startswith('%RANGE'):
                # E.g. %RANGE 2012, 1996
                # --> Adds children: 2012, 2011, ..., 1997, 1996
                a, b = [int(x) for x in left[6:].split(',')]
                r = range(a, b + 1) if a <= b else range(a, b - 1, -1)
                children.extend([str(x) for x in r])
            else:
                raise Exception('Nepoznata naredba: ' + left)
        else:
            # Child definition: var_value1/var_value2/.../var_valueN
            children.append(left)

    created = 0
    existing = 0
    for index, x in enumerate(children):
        # Update vars with child var values. (values are stripped!)
        vars.update({k: v.strip() for k, v in zip(var_names, x.split('/'))})

        # Update additional vars
        for var in var_formats:
            # Note we are using same dictionary that is being updated, that's
            # why order matters
            vars[var[0]] = var[1].format(**vars)

        try:
            # Check if folder with the same name, short name and parent exists.
            folder = Folder.objects.get(parent=parent, name=vars['name'],
                    short_name=vars['short'])
            existing += 1
        except:
            # If not, create new folder.
            folder = Folder(author=author, parent=parent, parent_index=index,
                hidden=False, editable=False, name=vars['name'],
                short_name=vars['short'])
            folder.save()
            created += 1

        # Note that the object has to exist to use this!
        set_tags(folder, vars['tags'])
        # TODO: call folder._refresh_cache_tags() on change signal.

        # Call recursion if there is any level left
        if rest:
            # Note that parent changed!
            _c, _e = _create_folders(author, folder, rest, _dict_to_object(vars))
            created += _c
            existing += _e

    return created, existing
示例#9
0
def folder_inline_year_shortcuts(context, folder_descriptors, split=1000):
    """
        Output links to folders and their (year-like) children in format:
            Parent folder with a long name          (main folder)
            '05 '06 '07 ... '12                     (year folders/children)

        folder_descriptors is a list of descriptions, one for each folder, where
        a description is a human readable info that uniquely describes the
        folder.
        When `split` parameter is given, result will be divided into
        `split`-sized results

        Currently, description is a string of comma-separated tags.
        For example: 'IMO' represent the main folder containing all IMO tasks.

        Optionally, the string can contain + sign, which is replaced with
        user's selected tag (from school class).
    """
    user = context.get('user')

    school_class = user and user.is_authenticated() \
        and user.get_profile().school_class

    chosen_tag = school_class and   \
        next((x[2] for x in settings.USERPROFILE_SCHOOL_CLASS_INFO \
            if x[0] == school_class), None)

    # Replace + with chosen tag (appropriate school class)
    if chosen_tag:
        folder_descriptors = [x.replace('+', chosen_tag) for x in folder_descriptors]

    # Find all main folders
    main_folders = _descriptors_to_folders(folder_descriptors)
    ids = [x.id for x in main_folders]

    # Find all year folders
    year_children = defaultdict(list)
    children = Folder.objects.filter(parent_id__in=ids)
    for x in children:
        # If a year-like folder
        if x.short_name.isdigit():
            year_children[x.parent_id].append(x)

    all_folders = main_folders[:]

    # Pick only last X years for each of the main folders
    for key, value in year_children.iteritems():
        _sorted = sorted(value, key=lambda x: x.name, reverse=True)
        _sorted = _sorted[:settings.FOLDER_INLINE_YEAR_COUNT][::-1]
        year_children[key] = _sorted
        all_folders.extend(_sorted)

    # Get user's statistics for all of these folder. That's the whole
    # purpose of this inline year shortcuts.
    user_stats = Folder.many_get_user_stats(all_folders, user)
    for x in all_folders:
        # Keep only last two digits
        x.t_short_year_name = "'" + x.short_name[-2:]

        stats = user_stats.get(x.id)
        solvable_task_count = stats and stats[1]

        any, any_non_rated, percent, RGB =  \
            Folder.parse_solution_stats(stats and stats[2], solvable_task_count)

        # Main folder
        if any and x.id in year_children:
            plus_sign = '+' if any_non_rated else ''
            x.t_percent_str = mark_safe(
                '<span style="color:#%02X%02X%02X;">(%s%d%%)</span>'    \
                    % (RGB[0], RGB[1], RGB[2], plus_sign, 100 * percent))
        x.t_color = '#%02X%02X%02X' % RGB

    # Stick children to main folders:
    for x in main_folders:
        x.t_year_children = year_children[x.id]

    return {
        'main_folder_chunks': [main_folders[i:i + split]  \
            for i in range(0, len(main_folders), split)],
    }
示例#10
0
 def get_queryset(self):
     return Folder.foruser(self.request.user)
示例#11
0
 def get_context_data(self, *args, **kwargs):
     ctx = super(TemplateView, self).get_context_data(*args, **kwargs)
     ctx['folders'] = Folder.foruser(self.request.user).filter(level__lte=3)
     return ctx