"importerror: Cannot Import Name Mail" In Flask
Solution 1:
You have a circular dependency. You have to realize what Python is doing when it imports a file.
Whenever Python imports a file, Python looks to see if the file has already started being imported before. Thus, if module A imports module B which imports module A, then Python will do the following:
- Start running module A.
- When module A tries to import module B, temporarily stop running module A, and start running module B.
- When module B then tries to import module A, then Python will NOT continue running module A to completion; instead, module B will only be able to import from module A the attributes that were already defined there before module B started running.
Here is app/__init__.py
, which is the first file to be imported.
from flask import Flask
app = Flask(__name__)
from app import index # <-- See note below.from flask.ext.mail import Mail
mail = Mail(app)
When this file is imported, it is just Python running the script. Any global attribute created becomes part of the attributes of the module. So, by the time you hit the third line, the attributes 'Flask' and 'app' have been defined. However, when you hit the third line, Python begins trying to import index
from app
. So, it starts running the app/index.py
file.
This, of course, looks like the following:
from flask.ext.mail import Message
from app import app, mail # <-- Error herefrom flask import render_template
from config import ADMINS
from decorators importasync
Remember, when this Python file is being imported, you have thus far only defined Flask
and app
in the app
module. Therefore, trying to import mail
will not work.
So, you need to rearrange your code so that if app.index
relies on an attribute in app
, that app
defines that attribute before attempting to import app.index
.
Solution 2:
This is probably the problem:
from app import app, mail
In the file 'app/emails.py' the import is from the current module, not a nested app module. Try:
from . import app, mail
If it doesn't work, you should update your question with a more detailed directory listing.
Post a Comment for ""importerror: Cannot Import Name Mail" In Flask"