ImportError:无法导入名称' app'与Flask

时间:2017-09-13 10:11:40

标签: python flask flask-mail

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'

1 个答案:

答案 0 :(得分: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