Table 'user' is already defined for this MetaData instance 疑问

在进行flask数据库连接时,发现一个问题:当models.py里面采用from app import db引入db时,运行models.py会报错如下:

sqlalchemy.exc.InvalidRequestError: Table 'users' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

models.py里代码如下:

from app import db #db 是在app/__init__.py生成的关联后的SQLAlchemy实例

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    email = db.Column(db.String(64), unique=True)
    password = db.Column(db.String(64), nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username
       
if __name__ == '__main__':
	db.create_all()

而app/init.py代码如下:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

如果不采用from app import db,而是直接在models.py文件中定义app和db就不会报错,例如models.py直接改成如下运行就不会报错了:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    email = db.Column(db.String(64), unique=True)
    password = db.Column(db.String(64), nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username
       
if __name__ == '__main__':
	db.create_all()

如果实在要让models.py里面采用from app import db引入db,也是可以的,只要注意不直接运行models.py就好了。可以新建一个文件create_db.py来新建表:

# create_db.py
from app import db
db.create_all()

models.py还是像原先那样,然后直接运行create_db.py就不会报错,建表成功。

这是为什么呢???我还是不清楚。。。
我查了很久的资料,找到一个有点像的原因:

I had a similar error. 
My problem was importing the class that inherits db.Model from two different files using a relative import. 
Flask-SQLAlchemy mapped the two imports as two different table definitions and tried to create two tables.
I fixed this issue by using the absolute import path in both files.

但我还不是很理解。可能以后会理解吧。
如果有大佬知道原因的麻烦告知一下我,感谢感谢!!!

Table 'user' is already defined for this MetaData instance 疑问Table 'user' is already defined for this MetaData instance 疑问 achiv 发布了9 篇原创文章 · 获赞 4 · 访问量 3530 私信 关注
上一篇:学习笔记-移植U-boot 2012 04 01 到JZ2440(2.1)——启动过程概述


下一篇:”echarts is not defined ” 解决办法