问题
I'm new to flask, and have problem with importing db while running from python console/cmd.
I'm facing this error :
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)
The tree of my project :
Flask/
app/
__init__.py
forms.py
models.py
routes.py
__init__.py
config.py
Flask.py
Flask/init.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)
When running flask run via command it's working fine. But I when I'm trying to run via python console or cmd I'm not able to run successfully. Thanks
回答1:
there is a problem when importing module fix this....
inside Flask remove the __init_.py here u didnt want a init file.if the Flask folder is the root folder others are sub folders inside it I guess your main file is Flask.py. So change the
from Flask.app import db
to
from app import db
considering db is declared inside app/init.py
来源:https://stackoverflow.com/questions/59505046/error-while-importing-module-app-using-from-flask-app-import-db