Python2.7(flask) reference to import variable from

2019-09-19 02:27发布

I need to import a variable that is initialized in the __init__.py of my package.

======__init__.py======
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager


basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)

app.config['SECRET_KEY'] = 'blah'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'thermos.db')
app.config['DEBUG'] = True
db = SQLAlchemy(app)

app.config['DEBUG'] = True

import models
import views

Then in my views.py and my models.py I am trying to import db and app like so:

===== views.py ====
from thermos import app, db

This is not working as I would expect. At the moment my directory structure looks like this:

/thermos
   /thermos
      __init__.py
      views.py
      models.py

The tutorial I am using uses the exact setup I have listed above, however it does not work for me. To get the code to work I have to make the following changes:

===== views.py ====
from . import app, db

===== models.py ====
from . import db

Why isn't it working for me? Is my change acceptable? I don't like to use relative links. Halp? Thanks!

The error in question:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from thermos import app
  File "/home/python/projects/plural_flask/thermos/thermos/__init__.py", line 16, in <module>
    import models
  File "/home/python/projects/plural_flask/thermos/thermos/models.py", line 5, in <module>
    from thermos import db
ImportError: cannot import name db

I have already read these: Flask structure -- can't import application from __init__.py Python: How to import from an __init__.py file?

and many others, but still can't figure out why it works for the tutorial I'm following and not on my own machine with the same setup.

1条回答
▲ chillily
2楼-- · 2019-09-19 02:47

My answer comes from another stackoverflow answer: Python circular importing?

Essentially use import db rather than from thermos import db

查看更多
登录 后发表回答