Skip to content

Instantly share code, notes, and snippets.

@andik
Last active January 22, 2024 19:12
Show Gist options
  • Save andik/e86a7007c2af97e50fbb to your computer and use it in GitHub Desktop.
Save andik/e86a7007c2af97e50fbb to your computer and use it in GitHub Desktop.
Flask directory listing
<!doctype html>
<title>Path: {{ tree.name }}</title>
<h1>{{ tree.name }}</h1>
<ul>
{%- for item in tree.children recursive %}
<li>{{ item.name }}
{%- if item.children -%}
<ul>{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
def make_tree(path):
tree = dict(name=os.path.basename(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=name))
return tree
import os
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def dirtree():
path = os.path.expanduser(u'~')
return render_template('dirtree.html', tree=make_tree(path))
if __name__=="__main__":
app.run(host='localhost', port=8888, debug=True)
@ilovefreesw
Copy link

What if I need files to be clickable?

@thompsonkylaw
Copy link

What if I need files to be clickable?
usd a tag

  • {{ item.name }}
  • @bwakyaya
    Copy link

    bwakyaya commented Mar 3, 2022

    How do I make the tree nodes to toggle?

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment