从Flask.app import db导入模块应用程序时出错

时间:2019-12-27 19:07:36

标签: python-3.x flask flask-sqlalchemy python-import

我是flask的新手,从python console / cmd运行时导入数据库时​​遇到问题。

我遇到此错误:

In[67]: os.getcwd()
Out[67]: 'C:\\Users\\Desktop\\Python\\Flask'
In[68]: os.listdir()
Out[68]: 
['app',
 'app.db',
 'config.py',
 'Flask.py',
 'migrations',
 'venv',
 '__init__.py',
 '__pycache__']

In[69]: from Flask.app.models import User,Post
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-69-dca3714f084d>", line 1, in <module>
    from Flask.app.models import User,Post
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\Desktop\Python\Flask\app\models.py", line 1, in <module>
    from Flask.app import db
ImportError: cannot import name 'db' from 'Flask.app' (C:\Users\Desktop\Python\Flask\app\__init__.py)

我的项目的树:

Flask/
  app/
    __init__.py
    forms.py
    models.py
    routes.py
  __init__.py
  config.py
  Flask.py

烧瓶/ 初始化 .py



app / init .py

from flask import Flask
from Flask.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)
migrate = Migrate(app, db)

from Flask.app import routes, models

app / models.py

from Flask.app import db
from datetime import datetime


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return '<User {}>'.format(self.username)

通过命令运行烧瓶时,它运行正常。但是当我尝试通过python控制台或cmd运行时,我无法成功运行。 谢谢

1 个答案:

答案 0 :(得分:0)

导入模块时存在问题。...

在Flask里面删除__init_.py,你不想要一个初始化文件。如果Flask文件夹是根文件夹,其他是其中的子文件夹,我猜你的主文件是Flask.py。所以 更改

from Flask.app import db

from app import db

考虑db在app / init.py中声明