Flask-Admin 刷新文件列表

Flask-Admin refresh files list

Flask-Admin form tutorial code 从目录中的文件创建列表。这是列表的填充:

def build_sample_db():
    # Populating the pdf files 
    db.drop_all()
    db.create_all()

    for i in [1, 2, 3]:
        file = File()
        file.name = "Example " + str(i)
        file.path = "example_" + str(i) + ".pdf"
        db.session.add(file)
    db.session.commit()
    return

if __name__ == '__main__':
    # Build a sample db on the fly, if one does not exist yet.
    build_sample_db()
    # Start app
    app.run(debug=True)

我已将填充代码更改为:

# get all files in a directory
def build_sample_db():
    db.drop_all()
    db.create_all()
    # It lists the files in a directory 
    ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
    for f in ls_output:
        file = File()
        file.path = f
        db.session.add(file)

    db.session.commit()
    return

它列出了没有硬编码值的整个目录。但它仅在应用程序启动时刷新。

Forms in Flask-Admin 是示例及其外观。

此处新增视图:

 admin.add_view(FileView(File, db.session))

文件视图:

class FileView(sqla.ModelView):
    # Pass additional parameters to 'path' to FileUploadField constructor
    form_args = {
        'path': {
            'label': 'File',
            'base_path': file_path,
            'allow_overwrite': False
        }
    }
    # No
    def __init__():
        db.drop_all()
        db.create_all()
        ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
        for f in ls_output:
            file = File()
            file.path = f
            db.session.add(file)
        db.session.commit()

在哪里添加填充代码,以便刷新并重新获取目录中的文件?数据库也将被重新创建,只是为了这个例子。 我不想创建新视图,而是要刷新它。

覆盖视图的 index_view 方法。类似(未经测试)的东西:

from flask_admin import expose

class FileView(sqla.ModelView):
    # Pass additional parameters to 'path' to FileUploadField constructor
    form_args = {
        'path': {
            'label': 'File',
            'base_path': file_path,
            'allow_overwrite': False
        }
    }

    @expose('/')
    def index_view(self):
        db.drop_all()
        db.create_all()
        ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
        for f in ls_output:
            file = File()
            file.path = f
            db.session.add(file)
        db.session.commit()
        return super(FileView, self).index_view()

Flask-Admin file example 也回答了这个问题。文件刷新,只有数据库没有添加,但没关系:

from flask_admin.contrib import fileadmin
# irrelevant code removed - see in the link 
if __name__ == '__main__':
    # Create directory
    path = op.join(op.dirname(__file__), 'files')
    try:
        os.mkdir(path)
    except OSError:
        pass

    # Create admin interface
    admin = admin.Admin(app, 'Example: Files')
    # Another way to add view
    admin.add_view(fileadmin.FileAdmin(path, '/files/', name='Files'))

    # Start app
    app.run(debug=True)