用flask列出目录中的文件 [英] 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>
但是它不起作用,链接不好.Wheareas我想要一个链接到 http://192.168.0.70:5000/static/repertory/subrepertory/file
,我有一个链接到 http://192.168.0.70:5000/file
,导致404.有人可以帮我吗?
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 ?
推荐答案
尝试一下:
<ul><a href="/static/{{ loop(item.children) }}">{{ loop(item.children) }}</a></ul>
我刚刚在 href ="
之后, {{
]之前直接添加了所需的静态路径.
I just added the static path that you need directly after href="
, before {{
.
执行此操作的另一种方法是,已经在make_tree函数中添加了路径的所需部分.
Another way you can do this is to add the add the needed part of the path in your make_tree function already.
让make_tree()看起来像这样:
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.
这篇关于用flask列出目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!