Shan-x
Shan-x

Reputation: 1176

List files in directories with flask

I’d like to list the files which are in directories and subdirectories. I have used this answer to have the list, but the items are non-clickables, so I’d like to add a link between the name of the files and their locations. I have try to modify the template with something like this :

<!doctype html>
<title>Path: {{ tree.name }}</title>
<h1>{{ tree.name }}</h1>
<ul>
{%- for item in tree.children recursive %}
    <li><a href="{{ item.name }}">{{ item.name }}</a>
    {%- if item.children -%}
        <ul><a href="{{ loop(item.children) }}">{{ loop(item.children) }}</a></ul>
    {%- endif %}</li>
{%- endfor %}
</ul>

But it doesn’t work, the links are not good. Wheareas I want a link to http://192.168.0.70:5000/static/repertory/subrepertory/file, I have a link to http://192.168.0.70:5000/file, which leads to a 404. Can somebody help me ?

Upvotes: 8

Views: 21008

Answers (1)

HolgerSchurig
HolgerSchurig

Reputation: 2973

Try this:

<ul><a href="/static/{{ loop(item.children) }}">{{ loop(item.children) }}</a></ul>

I just added the static path that you need directly after href=", before {{.

Another way you can do this is to add the add the needed part of the path in your make_tree function already.

EDIT:

let make_tree() look like this:

def make_tree(path):
    tree = dict(name=path, children=[])
    try: lst = os.listdir(path)
    except OSError:
        pass #ignore errors
    else:
        for name in lst:
            fn = os.path.join(path, name)
            if os.path.isdir(fn):
                tree['children'].append(make_tree(fn))
            else:
                tree['children'].append(dict(name=fn))
    return tree

Then it returns full path names and not just file names.

Upvotes: 5

Related Questions