What is the correct way to solve this circular import error with a Flask blueprint?

前端 未结 1 1819
梦谈多话
梦谈多话 2020-12-18 01:23

I had a problem with a circular import, so I moved my blueprint import below my app definition. However, I\'m still having an import error.

Traceback (most          


        
1条回答
  •  隐瞒了意图╮
    2020-12-18 02:15

    You have a circular import in your code. Based on the traceback:

    1. app.py does from views import site
    2. views.py does from models import User
    3. models.py does from database_setup import db
    4. database_setup.py does from app import app
    5. app.py does from views import site

    Based on these order of events, the app.py you've posted isn't the one that's actually causing your problem. Right now, app hasn't been defined before views is imported, so when further down the chain it tries to get app, it's not available yet.

    You need to restructure your project so that everything that depends on app is imported after app is defined. From your question, it seems like you think you did, but perhaps there's still an import written above app that you missed.


    Probably unrelated, but you are currently using "relative" imports, which are discouraged. Rather than doing from views import site, etc., you should do an absolute path: from app.views import site, or a relative path: from .views import site.


    To answer the initial question of "is using __main__ to import blueprints a good idea?", it is not. The problem with that is that the __main__ guard is only executed when you run the module directly. When you go to deploy this using a real app server such as uWSGI or Gunicorn, none of your blueprints will be imported or registered.

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