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()
在哪里添加用于填充的代码,以便可以刷新并重新获取目录中的文件?数据库也将重新创建,仅用于示例。 我不想创建新视图,但要刷新它。
答案 0 :(得分:1)
覆盖视图的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()
答案 1 :(得分:0)
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)