伸缩自如的Flask [day3] Factory mode

首先,我们一样可以来谈谈为什麽需要使用工厂模式。
过去,你使用了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'] = '[email protected]'
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'] = '[email protected]'
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='[email protected]'
    msg = Message('Here is subject.', sender = '[email protected]', 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 = '[email protected]@gmail.com', recipients = [ '[email protected]'])
    msg.body = 'hello hello hello'

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

现在你可以同时扩展你的服务同时自在的寄信了,甚至不止是寄信的功能。
要我说的话当开始使用blue_print之後,为了要能让程序能正常运作,所以你就会自然的使用到Factory mode了。
第三天就先到这里,谢谢。


<<:  台湾需要1500位CISSP!

>>:  进击的软件工程师之路-软件战斗营 第十一周

第21天~OKHttp

OKHttp -网路下载传输资料 开新档案- 找到网站 https://square.github....

用 Python 畅玩 Line bot - 24:Flask(二)

mongoDB 除了可以让 line bot 使用之外,flask同样也可以去透过 pymongo ...

Rust-定义泛型结构

既然有泛型函数当然少不了泛型结构 struct S1<T1, T2> { n1: T1,...

Day 19:怎麽在 Angular 专案中使用 nvm 切换 Node.js 版本

前一篇谈到了 Angular 版本如何更新的议题,今天依然讨论跟版本相关的议题:如何在 Angula...

网路是怎样连接的(十一) 初探IP协议

思考重点 封包是如何找到下一个端节点的 IP地址在封包转发中扮演的角色 MAC地址在封包转发中扮演的...