2

我的配置有问题Flask-Mail

这是我的目录结构:

▾ app/
  ▾ controllers/
      __init__.py
      mail.py
▾ config/
    __init__.py
▾ run.py

在我的 run.py 中,我有:

from app import app

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

配置在config/__init__.py

import os
DEBUG = True
SECRET_KEY = 'my precious'
PORT = int(os.environ.get('PORT', 5000))
MAIL_SERVER = 'ssl0.foo.net'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = 'contact@foo.bar'
MAIL_PASSWORD = 'EwCa2kd'

配置加载在app/__init__.py

import logging

from flask import Flask
from app.controllers import pages
from flask_mail import Mail

app = Flask(__name__)
app.config.from_object('config.development')

app.register_blueprint(pages.blueprint)

app.logger.setLevel(logging.NOTSET)
mail = Mail(app)

我想创建一个邮件controllers/mail.py控制器

from flask_mail import Message
from .. import app, mail

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    mail.send(msg)

但我不能mail在这个控制器中使用,我尝试了几种组合,但我得到了一些导入错误,比如:ImportError: cannot import name 'app'

4

1 回答 1

1

我认为你需要的是 current_app。它可以导入为:

from flask import current_app

阅读http://flask.pocoo.org/docs/0.12/api/#flask.current_app了解更多信息。

然后使用:

with current_app.app_context():
    # mail sending logic goes here
于 2017-09-14T12:36:41.173 回答