Bor Bor - 3 months ago 39
Python Question

Flask-Admin refresh files list

The Flask-Admin form tutorial code creates a list from the files in a directory. This is the populating of the list:

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)


I've changed the code for populating to this:

# 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


It lists the whole directory without hard-coded values. But it refreshes only on the start of the app.

Forms in Flask-Admin is the example and how it looks.

The view is added here:

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


Files view:

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()


Where to add the code for populating, so it can be refreshed and the files in the dir taken again? Database would be recreated as well just for the example.
I don't want to create a new view, but to refresh this.

Answer

Override your view's index_view method. Something like (untested) :

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()