首页 > 代码库 > flask-uploads扩展的使用笔记

flask-uploads扩展的使用笔记

涉及的flask扩展
flask-uploadsflask的一个文件上传扩展, 提供了UploadSet这个概念
flask-wtf(中文)很强大的表单的扩展
flask-bootstrapbootstrap的flask扩展, 结合模版使用, 此处用到quick_form功能

 

from flask import Flask, render_templatefrom flask_uploads import UploadSet, IMAGES, configure_uploadsfrom flask_wtf import Formfrom wtforms import SubmitFieldfrom flask_wtf.file import FileField, FileAllowed, FileRequiredfrom flask_bootstrap import Bootstrapapp = 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_mypicconfigure_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文件:

1 {% import "bootstrap/wtf.html" as wtf %}2 3 {% block page_content %}4     <h4>uploaded: {% if url %} {{url}}{% endif %}</h4>5     {{ wtf.quick_form(form, enctype="multipart/form-data") }} 6 {% endblock page_content %}

 

flask-uploads扩展的使用笔记