您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關flask怎么實現文件上傳與郵件發送,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
一、原生文件上傳
form.html
<img src="{{ url_for('static',filename='img/17.jpg') }}" width="300" alt=""> <form action="" method="post" enctype="multipart/form-data"> <p>修改頭像 <input type="file" name="file"></p> <p><input type="submit" value="提交"></p> </form>
manage.py
#文件上傳的視圖函數 @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) # 獲取圖片大小 # 設置尺寸 img.thumbnail((128, 128)) # 當前縮放不是等比縮放 變成等比縮放 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) # 獲取圖片大小 # 設置尺寸 img.thumbnail((128, 128)) # 當前縮放不是等比縮放 變成等比縮放 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()
二、發送郵件 flask-mail
pip install flask-mail
設置臨時環境變量
windows set 名=值
Ubuntu下 export 名=值
注意: 名和值都不用加引號
單線程發送郵件
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' # 為了保密 將郵箱賬號和授權碼都加入到了臨時環境變量中 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 '發送郵件' if __name__ == '__main__': manager.run()
異步發送郵件
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,)) #創建線程 參數1為創建子線程 參數2為傳遞參數 類型為元組 thr.start() #開啟線程 return '發送郵件' def async_send_mail(msg): #開啟程序上下文 把當前請求 作為同一個請求 with app.app_context(): mail.send(message=msg) if __name__ == '__main__': manager.run()
以上就是flask怎么實現文件上傳與郵件發送,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。