python flask浏览带有文件的目录

2024-05-15 12:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使用flask浏览包含文件的目录?

当字符串之间出现奇怪的附加时,我的代码似乎永远无法正常工作。

我也不知道如何实现一种检查路径是文件还是文件夹的方法。

这是我的烧瓶应用程序。路径:

@app.route('/files', defaults={'folder': None,'sub_folder': None}, methods=['GET'])
@app.route('/files/<folder>', defaults={'sub_folder': None}, methods=['GET'])
@app.route('/files/<folder>/<sub_folder>', methods=['GET'])

    def files(folder,sub_folder):
        basedir = 'files/'
        directory = ''

        if folder != None:
            directory = directory + '/' + folder

        if sub_folder != None:
            directory = directory + '/' + sub_folder

        files = os.listdir(basedir + directory)

        return render_template('files.html',files=files,directory=basedir + directory,currdir=directory)

这是我的html模板,如果有人能给我一些指针,这将是非常感谢!

<body>
    <h2>Files {{ currdir }}</h2> </br>
    {% for name in files: %}
        <A HREF="{{ directory }}{{ name }}">{{ name }}</A> </br></br>
    {% endfor %}
</body>s.html',files=files,directory=basedir + directory,currdir=directory)

Tags: 文件namebr路径noneappgethtml
2条回答

url结构中的path转换器(docs链接)比硬编码所有不同的可能路径结构要好。

可以使用os.path.exists检查路径是否有效,使用os.path.isfileos.path.isdir分别检查路径是文件还是目录。

终结点:

@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
    BASE_DIR = '/Users/vivek/Desktop'

    # Joining the base and the requested path
    abs_path = os.path.join(BASE_DIR, req_path)

    # Return 404 if path doesn't exist
    if not os.path.exists(abs_path):
        return abort(404)

    # Check if path is a file and serve
    if os.path.isfile(abs_path):
        return send_file(abs_path)

    # Show directory contents
    files = os.listdir(abs_path)
    return render_template('files.html', files=files)

模板:

<ul>
    {% for file in files %}
    <li><a href="{{ file }}">{{ file }}</a></li>
    {% endfor %}
</ul>

注:abortsend_file函数是从烧瓶中导入的。

这是一个有效的例子。

# app.py
from flask import Flask 
from flask_autoindex import AutoIndex

app = Flask(__name__)

ppath = "/" # update your own parent directory here

app = Flask(__name__)
AutoIndex(app, browse_root=ppath)    

if __name__ == "__main__":
    app.run()

这是一份有效的回购协议

相关问题 更多 >