【发布时间】:2019-02-14 23:05:06
【问题描述】:
我有一个 Flask 应用程序,当它应该失败时通过用户输入验证。我在应用程序的另一部分有类似的代码,效果很好。似乎没有调用 FileAllowed() 方法。或者,如果是,它会返回 true。
此代码将用户文件上传到 s3。
MultipleFileField() 方法仅对图像文件扩展名进行验证检查。但是,任何文件都会通过此检查。 InputRequired() 方法工作得很好。
我已经尝试了多种变体,但没有任何效果。这不是 CRSF 问题,因为其他具有类似代码的路由没有它也可以工作。
flask_wtf 形式:
class AddImgForm(FlaskForm): # should use InputRequired() not DataRequired()
images= MultipleFileField('Upload Images', validators=[InputRequired(),FileAllowed(['jpg', 'png', 'jpeg', 'tif'])])
submitBTN2 = SubmitField('Upload')
路线:
@users.route("/account", methods=['GET', 'POST'])
@login_required
def account():
form = UpdateAccountForm()
if form.validate_on_submit():
if form.picture.data: # if a picture is provided save picture
picture_file= save_picture(form.picture.data, 'p') # saves picture and returns dict with ['filepath'] and ['filename']
BUCKET= os.environ['BUCKET'] # should send to 'bucket-publicaccess/uploads' bucket in production
s3= boto3.resource("s3",
region_name = "us-east-2", # had to add "us-east-2" as incorrect region was generated
config= boto3.session.Config(signature_version='s3v4'), # must add this to address newer security
aws_access_key_id = os.environ["AWS_ACCESS_KEY_ID"],
aws_secret_access_key = os.environ["AWS_SECRET_ACCESS_KEY"]) # AWS Generated key pairs
s3.Bucket(BUCKET).upload_file(picture_file['filepath'], 'uploads/'+ picture_file['filename']) #upload to s3
current_user.image_file= 'uploads/'+picture_file['filename']
print(current_user.image_file)
os.remove(picture_file['filepath']) # remove file from tmp directory
current_user.username = form.username.data
current_user.email = form.email.data
db.session.commit() # commit changes
flash('Your account has been updated!', 'success')
return redirect(url_for('users.account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
image_file = current_user.image_file
return render_template('account.html', title='Account',
image_file=image_file, form=form)
HTML:
<form method="POST" action="" enctype="multipart/form-data" id="addImgForm">
{{ addImgForm.hidden_tag() }}
<fieldset class="form-group">
<div class="form-group">
{{ addImgForm.images.label() }}
{{ addImgForm.images(class="form-control-file") }}
{% if addImgForm.images.errors %}
{% for error in addImgForm.images.errors %}
<span class="text-danger">{{ error }}</span></br>
{% endfor %}
{% endif %}
</div>
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
{{ addImgForm.submitBTN2(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
任何帮助将不胜感激,因为大多数问题都与此失败有关,而此代码始终通过。
【问题讨论】:
-
InputRequired()不应该是FileRequired()吗? -
我不这么认为,因为
MultiFileField是 wtforms 的一个类,InputRequired()也是。我认为问题在于结合 wtforms 类和 flask_wtf 类。 WTForms 没有我能找到的内置FileAllowed验证器。所以我认为它只是跳过了方法。
标签: flask flask-wtforms wtforms