首页 > 解决方案 > 在文件数量增加时返回更新列表

问题描述

我想用列表中的新文件名返回更新后的列表,而不显式刷新服务器。这是我用烧瓶编写的后端代码:-

@app.route("/list")
def return_list():
    all_files = os.listdir(r'H:/JS/uploads/')
    files_without_extension = []

for file in all_files:
    temp = os.path.splitext(file)
    if(temp[1] == ".json" ):
        files_without_extension.append(temp[0].title())


print("Total number of files : {}".format(len(all_files)))
print(files_without_extension)

return jsonify(files_without_extension)

问题是当我刷新我的网页时,列表正在更新。如果目录中删除或添加了文件,我希望更新列表。

标签: pythonflask

解决方案


我认为您只能使用websockets来实现这一点。

另一种解决方案是定期更新页面。自己删除文件的用户将被重定向。

<meta http-equiv="refresh" content="5">

@app.route('/list')
def uploads_list():
    def _froot(fname):
        root,_ = os.path.splitext(fname)
        return root
    return jsonify(_froot(fname) for fname in glob.iglob('H:/JS/uploads/*.json'))

@app.route('/remove/<path:fname>', methods=['POST'])
def uploads_remove(fname):
    if os.path.exists(f'{fname}.json'):
        try:
            os.remove(f'{fname}.json')
        except OSError as err: pass
    return redirect(url_for('uploads_list'))

推荐阅读