ImportError: cannot import name 'app' with Flask

4.9k views Asked by At

I have an issue with the configuration of Flask-Mail.

Here is my directory structure:

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

In my run.py i have:

from app import app

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

The config is in 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 = '[email protected]'
MAIL_PASSWORD = 'EwCa2kd'

The config is loaded in the 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)

And I would like to create a mail controller in controllers/mail.py with

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)

But i can not use mail in this controller, i tried several combinations but i got some import error like : ImportError: cannot import name 'app'

1

There are 1 answers

0
Tevin Joseph K O On

I think what you need is current_app. It can be imported as:

from flask import current_app

Read http://flask.pocoo.org/docs/0.12/api/#flask.current_app for more info.

Then use:

with current_app.app_context():
    # mail sending logic goes here