“ImportError: cannot import name mail” in Flask

前端 未结 2 1073
鱼传尺愫
鱼传尺愫 2020-12-16 01:43

I have built is a simple web app with Flask and Python, which I intend to upload to Heroku.

When starting my app locally, with the following script:

         


        
相关标签:
2条回答
  • 2020-12-16 02:12

    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 here
    from flask import render_template
    from config import ADMINS
    from decorators import async
    

    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.

    0 讨论(0)
  • 2020-12-16 02:16

    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.

    0 讨论(0)
提交回复
热议问题