【问题标题】:List files in directories with flask使用烧瓶列出目录中的文件
【发布时间】:2013-07-23 14:32:32
【问题描述】:

我想列出目录和子目录中的文件。我使用this answer 来获得列表,但这些项目是不可点击的,所以我想在文件名称和它们的位置之间添加一个链接。我尝试用这样的东西修改模板:

<!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>

但是不行,链接不好。当我想要一个指向 http://192.168.0.70:5000/static/repertory/subrepertory/file 的链接时,我有一个指向 http://192.168.0.70:5000/file 的链接,它会导致 404。有人可以帮助我吗?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    试试这个:

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

    我刚刚在href=" 之后,{{ 之前添加了您需要的静态路径。

    另一种方法是在 make_tree 函数中添加添加路径所需的部分。

    编辑:

    让 make_tree() 看起来像这样:

    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
    

    然后它返回完整的路径名,而不仅仅是文件名。

    【讨论】:

    • 确实可以添加/static。但我不能添加repertory/subrepertory,因为它是动态的(它们很少,并不总是相同)。
    • 所以在模板中添加“/static”,并在make_tree 函数中添加曲目/任何内容!
    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2018-09-25
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多