本篇文章給大家分享的是有關(guān)flask怎么實現(xiàn)文件上傳與郵件發(fā)送,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價值的長期合作伙伴,公司提供的服務(wù)項目有:國際域名空間、網(wǎng)頁空間、營銷軟件、網(wǎng)站建設(shè)、福建網(wǎng)站維護(hù)、網(wǎng)站推廣。一、原生文件上傳
form.html
manage.py
#文件上傳的視圖函數(shù) @app.route('/upload/',methods=['GET','POST']) def icon(): img_name = None if request.method == 'POST' and 'file' in request.files: # return '有文件上傳了' file = request.files.get('file') filename = file.filename #拿到文件名稱 #圖片上傳保存的路徑 imgPath = os.path.join(os.getcwd(), 'static/upload/'+filename) file.save(imgPath) img_name = filename return render_template('user/change_icon.html',img_name=img_name)
使用wtf和bootstrap渲染文件上傳
from flask import Flask,render_template,request from flask_script import Manager from flask_wtf import FlaskForm from flask_wtf.file import FileField,FileAllowed,FileRequired from wtforms import SubmitField from flask_uploads import UploadSet,patch_request_class,configure_uploads,IMAGES from flask_bootstrap import Bootstrap import os from PIL import Image app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1024*1024*64 app.config['SECRET_KEY'] = 'abcdef' app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(os.getcwd(),'static/upload') bootstrap = Bootstrap(app) file = UploadSet('photos',IMAGES) configure_uploads(app,file) patch_request_class(app,size=None) manager = Manager(app) #自定義一個文件上傳的表單類 class File(FlaskForm): photos = FileField('修改頭像',validators=[FileRequired(message='文件不能為空'),FileAllowed(file,message='該文件類型不允許上傳')]) submit = SubmitField('提交') @app.route('/') def index(): return render_template('index.html') #生成隨機的圖片名稱 def random_name(suffix,length=32): import string,random myStr = string.ascii_letters + '0123456789' return ''.join(random.choice(myStr) for i in range(length))+suffix @app.route('/upload/',methods=['GET','POST']) def icon(): form = File() img_url = None if form.validate_on_submit(): data = request.files.get('photos') suffix = os.path.splitext(data.filename)[-1] newName = random_name(suffix) file.save(data,name=newName) img_url = file.url(newName) img = Image.open(os.path.join(app.config['UPLOADED_PHOTOS_DEST'],newName)) print(img.size) # 獲取圖片大小 # 設(shè)置尺寸 img.thumbnail((128, 128)) # 當(dāng)前縮放不是等比縮放 變成等比縮放 img.save(os.path.join(app.config['UPLOADED_PHOTOS_DEST'],'s_'+newName)) return render_template('user/wtf-uplods.html',form=form,img_url=img_url) if __name__ == '__main__': manager.run()
模板中的代碼
from flask import Flask,render_template,request from flask_script import Manager from flask_wtf import FlaskForm from flask_wtf.file import FileField,FileAllowed,FileRequired from wtforms import SubmitField from flask_uploads import UploadSet,patch_request_class,configure_uploads,IMAGES from flask_bootstrap import Bootstrap import os from PIL import Image app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1024*1024*64 app.config['SECRET_KEY'] = 'abcdef' app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(os.getcwd(),'static/upload') bootstrap = Bootstrap(app) file = UploadSet('photos',IMAGES) configure_uploads(app,file) patch_request_class(app,size=None) manager = Manager(app) #自定義一個文件上傳的表單類 class File(FlaskForm): photos = FileField('修改頭像',validators=[FileRequired(message='文件不能為空'),FileAllowed(file,message='該文件類型不允許上傳')]) submit = SubmitField('提交') @app.route('/') def index(): return render_template('index.html') #生成隨機的圖片名稱 def random_name(suffix,length=32): import string,random myStr = string.ascii_letters + '0123456789' return ''.join(random.choice(myStr) for i in range(length))+suffix @app.route('/upload/',methods=['GET','POST']) def icon(): form = File() img_url = None if form.validate_on_submit(): data = request.files.get('photos') suffix = os.path.splitext(data.filename)[-1] newName = random_name(suffix) file.save(data,name=newName) img_url = file.url(newName) img = Image.open(os.path.join(app.config['UPLOADED_PHOTOS_DEST'],newName)) print(img.size) # 獲取圖片大小 # 設(shè)置尺寸 img.thumbnail((128, 128)) # 當(dāng)前縮放不是等比縮放 變成等比縮放 img.save(os.path.join(app.config['UPLOADED_PHOTOS_DEST'],'s_'+newName)) return render_template('user/wtf-uplods.html',form=form,img_url=img_url) if __name__ == '__main__': manager.run()
二、發(fā)送郵件 flask-mail
pip install flask-mail
設(shè)置臨時環(huán)境變量
windows set 名=值
Ubuntu下 export 名=值
注意: 名和值都不用加引號
單線程發(fā)送郵件
from flask import Flask,render_template from flask_script import Manager from flask_mail import Mail,Message import os app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.163.com' # 為了保密 將郵箱賬號和授權(quán)碼都加入到了臨時環(huán)境變量中 app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') mail = Mail(app) manager = Manager(app) @app.route('/send_mail/') def send_mail(): msg = Message(subject='大郎',recipients=['793390457@qq.com'],sender=app.config['MAIL_USERNAME']) msg.html = render_template('email/activate.html',username='大郎') mail.send(message=msg) return '發(fā)送郵件' if __name__ == '__main__': manager.run()
異步發(fā)送郵件
from flask import Flask,render_template from flask_script import Manager from flask_mail import Mail,Message import os from threading import Thread app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.163.com' app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') mail = Mail(app) manager = Manager(app) @app.route('/send_mail/') def send_mail(): msg = Message(subject='大郎',recipients=['793390457@qq.com'],sender=app.config['MAIL_USERNAME']) msg.html = render_template('email/activate.html',username='大郎') thr = Thread(target=async_send_mail,args=(msg,)) #創(chuàng)建線程 參數(shù)1為創(chuàng)建子線程 參數(shù)2為傳遞參數(shù) 類型為元組 thr.start() #開啟線程 return '發(fā)送郵件' def async_send_mail(msg): #開啟程序上下文 把當(dāng)前請求 作為同一個請求 with app.app_context(): mail.send(message=msg) if __name__ == '__main__': manager.run()
以上就是flask怎么實現(xiàn)文件上傳與郵件發(fā)送,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計公司行業(yè)資訊頻道。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。