您可以将目录树的生成和呈现分离为html。
要生成树,可以使用一个简单的递归函数: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
要将其呈现为html,可以使用jinja2的循环recursive功能:
Path: {{ tree.name }}{{ tree.name }}
{%- for item in tree.children recursive %}
{{ item.name }}{%- if item.children -%}
- {{ loop(item.children) }}
{%- endif %}
{%- endfor %}
将html放入templates/dirtree.html文件中。
要测试它,请运行以下代码并访问http://localhost:8888/: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)