flask入門4-檔案上傳與郵件傳送

rottengeek發表於2019-02-16

檔案上傳郵件傳送

一、原生檔案上傳

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入門5-model

相關文章