postgresql SQLAlchemy继承不起作用

14ifxucb  于 2023-02-15  发布在  PostgreSQL
关注(0)|答案(3)|浏览(142)

我正在使用Flask和SQLAlchemy。我已经使用了我自己的抽象基类和继承。当我尝试在python shell中使用我的模型时,我得到了以下错误:

>>> from schedule.models import Task
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/teelf/projects/schedule/server/schedule/models.py", line 14, in <module>
    class User(Base):
  File "/home/teelf/projects/schedule/server/venv/lib/python3.4/site-packages/flask_sqlalchemy/__init__.py", line 536, in __init__
    DeclarativeMeta.__init__(self, name, bases, d)
  File "/home/teelf/projects/schedule/server/venv/lib/python3.4/site-packages/sqlalchemy/ext/declarative/api.py", line 55, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "/home/teelf/projects/schedule/server/venv/lib/python3.4/site-packages/sqlalchemy/ext/declarative/base.py", line 254, in _as_declarative
    **table_kw)
  File "/home/teelf/projects/schedule/server/venv/lib/python3.4/site-packages/sqlalchemy/sql/schema.py", line 393, in __new__
    "existing Table object." % key)
sqlalchemy.exc.InvalidRequestError: Table 'user' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns
 on an existing Table object.

我该怎么解决这个问题?

    • 代码:**
    • 管理. py**:
#!/usr/bin/env python

import os, sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager

from server import create_app
from database import db

app = create_app("config")

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command("db", MigrateCommand)

if __name__ == "__main__":
    manager.run()
  • 初始化. py*:
from flask import Flask

from flask.ext.login import LoginManager

from database import db
from api import api
from server.schedule.controllers import mod_schedule

def create_app(config):
    # initialize Flask
    app = Flask(__name__)

    # load configuration file
    app.config.from_object(config)

    # initialize database
    db.init_app(app)

    api.init_app(app)

    # initialize flask-login
    login_manager = LoginManager(app)

    # register blueprints
    app.register_blueprint(mod_schedule)

    return app
    • 数据库. py**:
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()
    • 型号. py**:
from sqlalchemy.dialects.postgresql import UUID

from database import db

class Base(db.Model):
    __abstract__ = True

    id = db.Column(UUID, primary_key=True)

class User(Base):
    __tablename__ = "user"

    username = db.Column(db.String)
    password = db.Column(db.String)
    first_name = db.Column(db.String)
    last_name = db.Column(db.String)
    authenticated = db.Column(db.Boolean, default=False)

    def __init__(self, first_name, last_name, username):
        self.first_name = first_name
        self.last_name = last_name
        self.username = username

    def is_active(self):
        """ All users are active """
        return True

    def get_id(self):
        return self.username

    def is_authenticated(self):
        return self.authenticated

    def is_anonymous(self):
        """ Anonymous users are not supported"""
        return False
    • 控制器. py**:
from flask import Blueprint

from flask.ext.restful import reqparse, Resource

from api import api
from server.schedule.models import User

mod_schedule = Blueprint("schedule",  __name__, url_prefix="/schedule")

class Task(Resource):
    def put(self):
        pass

    def get(self):
        pass

    def delete(self):
        pass

api.add_resource(Task, "/tasks/<int:id>", endpoint="task")
wj8zmpe1

wj8zmpe11#

尝试添加

__table_args__ = {'extend_existing': True}

__tablename__=下的用户类
干杯

pzfprimi

pzfprimi2#

另一种选择是,如果你已经存在的数据库中没有数据,那么你可以删除它,重新创建一个没有表的数据库,然后交互式地运行你的“models.py“脚本(你需要在底部添加一些代码来实现这一点),然后在交互式Python控制台中执行“db.create_all()”,它应该会基于你的类创建表。

xmakbtuz

xmakbtuz3#

我有同样的问题,并在这里找到解决方案:https://github.com/pallets-eco/flask-sqlalchemy/issues/672#issuecomment-478195961
1.在磁盘上留下.pyc文件。

  1. Git忽略.gitignore中充满文件的空目录

相关问题