flask-uploads扩展的使用笔记

时间:2022-03-02 19:52:29
涉及的flask扩展
flask-uploads flask的一个文件上传扩展, 提供了UploadSet这个概念
flask-wtf(中文) 很强大的表单的扩展
flask-bootstrap bootstrap的flask扩展, 结合模版使用, 此处用到quick_form功能
from flask import Flask, render_template
from flask_uploads import UploadSet, IMAGES, configure_uploads
from flask_wtf import Form
from wtforms import SubmitField
from flask_wtf.file import FileField, FileAllowed, FileRequired
from flask_bootstrap import Bootstrap app = Flask(__name__) # 新建一个set用于设置文件类型、过滤等
set_mypic = UploadSet('mypic') # mypic # 用于wtf.quick_form()模版渲染
bootstrap = Bootstrap(app) # mypic 的存储位置,
# UPLOADED_xxxxx_DEST, xxxxx部分就是定义的set的名称, mypi, 下同
app.config['UPLOADED_MYPIC_DEST'] = './static/img' # mypic 允许存储的类型, IMAGES为预设的 tuple('jpg jpe jpeg png gif svg bmp'.split())
app.config['UPLOADED_MYPIC_ALLOW'] = IMAGES # 把刚刚app设置的config注册到set_mypic
configure_uploads(app, set_mypic) app.config['SECRET_KEY'] = 'xxxxx' # 此处WTF的SCRF密码默认为和flask的SECRET_KEY一样
# app.config['WTF_CSRF_SECRET_KEY'] = 'wtf csrf secret key' class UploadForm(Form):
'''
一个简单的上传表单
''' # 文件field设置为‘必须的’,过滤规则设置为‘set_mypic’
upload = FileField('image', validators=[
FileRequired(), FileAllowed(set_mypic, 'you can upload images only!')])
submit = SubmitField('ok') @app.route('/', methods=('GET', 'POST'))
def index():
form = UploadForm()
url = None
if form.validate_on_submit():
filename = form.upload.data.filename
url = set_mypic.save(form.upload.data, name=filename)
return render_template('index.html', form=form, url=url) if __name__ == '__main__':
app.run(debug=True)

html文件:

 {% import "bootstrap/wtf.html" as wtf %}

 {% block page_content %}
<h4>uploaded: {% if url %} {{url}}{% endif %}</h4>
{{ wtf.quick_form(form, enctype="multipart/form-data") }}
{% endblock page_content %}