Flask Getting Started file Upload flask-uploads (eight)

Source: Internet
Author: User

1 views passing multiple parameters

(1) Common parameters: Keyword parameter transfer

return render_template(‘模板名称.html‘,arg1=val1,arg2=val2...)

(2) Dictionary reference: In the form of a dictionary

dict= {    key1:value1,    key2:value2,    ....}return render_template(‘模板名称.html‘,dict)

(3) global variable G pass

In the View:

@app.route(‘/test‘)def test():    =‘张三‘    =‘男‘    return render_template(‘test.html‘)

In the template

<h2>{{ g.name }}</h2><h2>{{ g.sex }}</h2>

(4) Pass all local variables to template and use locals () * * To get the value of the variable directly

@app.route(‘/test‘)def test():    =‘张三‘    =‘男‘    return render_template(‘test.html‘,**locals())

In test.html

<h2>{{ name }}</h2><h2>{{ sex }}</h2>
2 Error page Customization
#制定捕获404和500的错误页面@app.errorhandler(404)def page_not_found(e):    return render_template(‘error.html‘,error=e,code=404)@app.errorhandler(500)def page_not_found(e):  #接受参数e,并传给错误error    return render_template(‘error.html‘,error=e,code=500)

Specify error page: Only one Error template page is required

{%‘common/boot_base.html‘%}{%%}{{ code }}  #标题显示500{%%}{%%}    <class="alert alert-danger" role="alert">{{ error }}  #显示错误页面信息</div>{%%}
3 File Upload

(1) Loading of static resources

{{ url_for(‘static‘,filename=‘img/mei.jpg‘) }} {{ url_for(‘static‘,filename=‘css/style.css‘) }} {{ url_for(‘static‘,filename=‘js/mei.js‘#注:static是内置的视图函数,我们通过其找到路由

(2) Native file upload

Template file

{% ifNewName%}#newName非空 Picture name passed in    <IMG SRC='{{url_for ("Static", Filename=newname)}}'Alt="'>{%endif%}#视图函数upLoad<Form action="{{url_for (' upLoad ')}}"Enctype=' Multipart/form-data 'Method=' Post '>    <input type=' file 'Name=' file '>    <P><input type=' Submit 'Value=' Submit '></P></Form>

Master File manage.py

 fromFlaskImportFlask,render_template,request fromFlask_scriptImportManager fromFlask_bootstrapImportBootstrapImportOs fromPILImportImage#python图片处理库App=Flask (__name__)#允许上传的后缀名, put the configuration fileapp.config[' Allowed_extensions ']=['. jpg ','. jpeg ','. png ','. gif ']#上传文件的大小app.config[' Max_content_length ']= 1024x768*1024x768* -#配置文件上传的路径app.config[' Upload_folder ']=OS.GETCWD ()+ '/static '#绑定bootstrapBootstrap=Bootstrap (APP) Manager=Manager (APP)@app. Route('/')defIndex ():returnRender_template (' index.html ')#生成随机图片名称的函数defNew_name (shuffix,length= +):ImportString,random mystr=String.ascii_letters+ ' 0123456789 'NewName= "'. Join (Random.choice (MYSTR) forIinch Range(length))returnNewName+Shuffix#定义判断后缀是否可用函数, return to True/falsedefAllowed_file (Shuffix):returnShuffixinchapp.config[' Allowed_extensions ']@app. Route('/upload ', Methods=[' GET ',' POST '])defUpload (): img_name= None    ifRequest.method== ' POST ':file =Request.files.get (' file ')#获取上传文件的名称FileName= file. filename#分割路径, returns a tuple of pathname and file name extensionShuffix=Os.path.splitext (filename) [-1]ifAllowed_file (Shuffix):#为真则生成随机名称NewName=New_name (Shuffix) img_name=NewName#拼凑完整的路径NewPath=Os.path.join (app.config[' Upload_folder '],newname)file. Save (NewPath)#处理图片的缩放Img=Image.Open(NewPath)#重新设置大小与尺寸Img.thumbnail (( $, $)) Img.save (NewName)#跳转上传页面并返回newName     returnRender_template (' upload.html ', NewName=Img_name)
4 flask-uploads Extension Library

Installation

pip3 install flask-uploads

class Uploadset : A collection of file upload configurations with three parameters:

Name: File Upload configuration collection, default files

Extensions: Upload file type, default DEFAULTS = TEXT + documents + IMAGES + DATA

Default_dest: The default storage path for uploading files, which we can specify by app.config[' uploads_default_dest ')

Method: Configure_uploads

After the application is configured, call this method, scan the upload configuration option and save it to our app, and register the upload module.

Let's look at the notation (flask-uploads library + FLASK-WTF Library)

Template file

{%  extends  ' common/base.html '  Span class= "OP" >% }  #继承  {%  block title % } home {%  endblock % }{%  import   ' bootstrap/wtf.html '  as  wtf % }  #导入  {%  Block page_content % } <  img src=   " {{  Url_for (' static ', filename=newname)  }}   " alt=   >  {{wtf.quick_form (form)}}  #快速渲染  {%  endblock % } 

Master boot File

 fromFlaskImportFlask,render_template,request fromFlask_scriptImportManager fromFlask_bootstrapImportBootstrapImportOs fromFlask_uploadsImportUploadset,images,configure_uploads,patch_request_class#导入库中验证的字段类 fromFlask_wtfImportFlaskform fromWtformsImportFilefield,submitfield fromFLASK_WTF.file ImportFileallowed,filerequiredapp=Flask (__name__)#允许上传的后缀app.config[' Secret_key ']= ' image 'app.config[' Max_content_length ']= 1024x768*1024x768* - #64兆#配置文件上传的路径app.config[' Uploaded_photos_dest ']=OS.GETCWD ()+'/static/upload '#实例化一个file对象 photos and photos to correspondfile =Uploadset (' photos ', IMAGES)the config configuration for the #将 app is registered to the Uploadset instance fileConfigure_uploads (App,file)#限制上传文件的大小 Size=none does not use the default size=64*1024*1024Patch_request_class (app,size=None) Bootstrap=Bootstrap (APP) Manager=Manager (APP)classFile (Flaskform):file =Filefield (' File Upload ', validators=[Filerequired (Message=' You have not selected a file '), fileallowed (file, message=' can only be rubbed on pictures ')]) Submit=Submitfield (' upload ')#生成随机图片名称的函数defNew_name (shuffix,length= +):ImportString, Random mystr=String.ascii_letters+ ' 0123456789 'NewName= "'. Join (Random.choice (MYSTR) forIinch Range(length))returnNewName+Shuffix@app. Route('/upload ', Methods=[' GET ',' POST '])defUpload (): Form=File () Img_url= None    #验证数据    ifForm.validate_on_submit (): Shuffix=Os.path.splitext (form.file. data.filename) [-1] NewName=New_name (Shuffix=Shuffix)file. Save (form.file. data,name=NewName) Img_url= file. URL (newName)returnRender_template (' boot_upload.html ', NewName=Img_url,form=Formif __name__ == ' __main__ ': Manager.run ()

Precautions:

python 将app的config配置注册到 UploadSet 实例file configure_uploads(app,file) 限制上传文件的大小 patch_request_class(app,size=None) file = UploadSet(‘photos‘,IMAGES) 实例化file对象继承了类中save() url() 内置方法 form = File() File类继承自FlaskForm 可以利用flask-uploads库进行验证 , 采用类File取代原生的Form表单访问通过 : 实例化form对象.字段名.data 访问字段对象 实例化form对象.字段名.data.属性名 访问字段对象对应的属性

Flask Getting Started file Upload flask-uploads (eight)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.