iT邦幫忙

0

伸縮自如的Flask [day3] Factory mode

  • 分享至 

  • xImage
  •  

首先,我們一樣可以來談談為什麼需要使用工廠模式。
過去,你使用了flask_mail這個套件來寫寄信的功能你的程式碼大概會長成這樣:

from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)
mail= Mail(app)

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'xxx@gmail.com'
app.config['MAIL_PASSWORD'] = 'xxx'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)

@app.route("/")
def index():
    msg = Message('Hello', sender = '@gmail.com', recipients = ['@gmail.com'])
    msg.body = "Hello Flask message sent from Flask-Mail"
    with app.open_resource("abc.jpg") as fp:
        msg.attach("abc.jpg", "image/jpg", fp.read())
    mail.send(msg)
    return "Sent"

if __name__ == '__main__':
   app.run(debug = True)

順便附上教學,如果你沒試著在flask中寄過信的話:
https://www.youtube.com/watch?v=GK6G8mbInI8&list=PLlu0Y7wV1aIqsuiTN6S-o5IfiN6Rkb1JH&index=8&t=41s

好的,你已經成功會寄信了,你信心滿滿的在你的blue_print中寫下了寄信功能:

from flask import Blueprint
from flask_mail import Mail, Message

testRoute = Blueprint('testRoute', __name__)

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'xxx@gmail.com'
app.config['MAIL_PASSWORD'] = 'xxx'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

mail= Mail(app)

@testRoute.route('/manu1')  #  路由拿掉剛才標上的生產
def testroute():
    ReviewEmail='wilsonsujames@gmail.com'
    msg = Message('Here is subject.', sender = 'rose.cefi@gmail.com', recipients = [ReviewEmail])
    msg.body = f"""
    OKOKOKOK
    OKOKOKOKOK
    """
    return '<h1>You win!</h1>'

執行了主程式,卻發現了一個錯誤:

NameError: name 'app' is not defined

也許這個時候該求助於Factory mode了,也許它可以幫助讓你的blue_print中的功能能正常使用:
https://github.com/wilsonsujames/factory_mode_flask

可以發現在該github的範例中,main.py為主程式:

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

而我們將所有的config都寫在app.py中,注意,是所有的config,以及所有blue_print註冊:

from flask import Flask
from api.func1 import func1_blueprint
from flask_mail import Mail, Message

def create_app():
    app = Flask(__name__)
    app.register_blueprint(func1_blueprint)
    
    app.config['MAIL_SERVER']='smtp.gmail.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USERNAME'] = ''
    app.config['MAIL_PASSWORD'] = ''
    app.config['MAIL_USE_TLS'] = False
    app.config['MAIL_USE_SSL'] = True

    mail= Mail(app)
    
    return app

而在blue_print中的function呢?我們使用flask 中的current_app來叫出寄信的功能:

from flask import Flask, request, Blueprint,jsonify,current_app
from flask_mail import Mail, Message

func1_blueprint = Blueprint('func1_blueprint', __name__)

@func1_blueprint.route('/')
def index():
    msg = Message('Hello', sender = 'xxx@gmail.com@gmail.com', recipients = [ 'xxx@gmail.com'])
    msg.body = 'hello hello hello'

    with current_app.app_context():
        mail = Mail()
        mail.send(msg)
    return 'Index hello.'

現在你可以同時擴展你的服務同時自在的寄信了,甚至不止是寄信的功能。
要我說的話當開始使用blue_print之後,為了要能讓程式能正常運作,所以你就會自然的使用到Factory mode了。
第三天就先到這裡,謝謝。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言