Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List files in directories with flask

Tags:

python

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 ?

like image 653
Shan-x Avatar asked Jul 24 '13 08:07

Shan-x


People also ask

How do I list files on a Flask?

You can list all files using os. listdir, glob. glob or the pathlib library. The result can then be output within a template.

How do I list files in a directory in Python?

To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3.

How do I access static files in Flask?

To reference the static files using the url_for() function, pass in the name of the directory – static in this case – and the keyword argument of filename= followed by your static file name. Flask automatically creates a static view that serves static files from a folder named static in your application's directory.


1 Answers

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.

like image 126
HolgerSchurig Avatar answered Sep 29 '22 14:09

HolgerSchurig