我只想将数据中的文件名写入模型。 如何从文件存储中获取文件名?
我正在将Flask用于我的Web应用程序。我创建包含FileField的表单。 对于我来说,获取相同的文件名很重要。
表格:
class TableForm(FlaskForm):
file = FileField('Add file', validators=[FileAllowed(['xlsx', 'xls', 'csv'])])
submit = SubmitField('Add file')
型号:
class Table(db.Model):
__table_args__= {'schema': 'app'}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(240), nullable=False)
table_file = db.Column(db.String(80), nullable=False)
路线:
@app.route("/projects/<int:project_id>", methods=['GET', 'POST'])
@login_required
def project_data_source(project_id):
tables = Table.query.filter_by(project_id=project_id)
if project.author != current_user:
abort(403)
form = TableForm()
if form.validate_on_submit():
table = Table(name=form.file.data, table_file=form.file.data)
db.session.add(table)
db.session.commit()
return redirect(url_for('project_data_source'))
答案 0 :(得分:0)
在their docs上有一个很好的例子。获取文件名的方法如下:
from werkzeug.utils import secure_filename
f = form.file.data
filename = secure_filename(f.filename)
因此您的代码必须是:
from werkzeug.utils import secure_filename
@app.route("/projects/<int:project_id>", methods=['GET', 'POST'])
@login_required
def project_data_source(project_id):
tables = Table.query.filter_by(project_id=project_id)
if project.author != current_user:
abort(403)
form = TableForm()
if form.validate_on_submit():
filename = secure_filename(form.file.data.filename)
table = Table(name=filename, table_file=filename) # not sure why you save it twice here
db.session.add(table)
db.session.commit()
return redirect(url_for('project_data_source'))