Flask:如何在SQLAlchemy中使用多个表

时间:2019-05-15 15:45:35

标签: python flask sqlalchemy

我的模型。py:

#  $ flask db migrate
# $ flask db upgrade
from ts import db,login
# encrypt the password
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin


class User(UserMixin,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))
    is_voted = db.Column(db.Boolean)
    is_admin=db.Column(db.Boolean)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def default_vote(self,is_voted):
        self.is_voted=False

    def default_authority(self,is_admin):
        self.is_admin=False

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

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

class Vote(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(64), index=True, unique=True)
    vote_num=db.Column(db.Integer)

    def vote_add(self,vote_num):
        vote_num=vote_num+1

    def __repr__(self):
        return '<Vote {}>'.format(self.name)


class ap_item(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(64), index=True)
    link=db.Column(db.String(128))

此文件中有3个表,并且已经迁移和升级了。

但是现在我可以使用以下脚本来更新表User

user = User(username="test", email="test@example")
user.set_password("password_test")
user.default_authority
user.default_vote
db.session.add(user)
db.session.commit()

当我尝试更新表Vote时,如下所示:

def ini_tutors():
    cxk_exist=Vote.query.filter_by(name='cxk').first()
    if cxk_exist==None:
        cxk=Vote(name='cxk',vote_num=0)
        db.session.add(cxk)
        db.session.commit()
    panda_exist=Vote.query.filter_by(name='panda').first()
    if panda_exist==None:
        panda=Vote(name='panda',vote_num=0)
        db.session.add(panda)
        db.session.commit()

它返回一条错误消息,

[parameters: ('susan', 'susan@example.com', 'pbkdf2:sha256:150000$CjbmEOm6$02e28253a378d7c2217f98a1b9a96bae58126d2ebd6efe5c12af60eb11328fdb', None)]

因此脚本正在尝试更新表User

这是否意味着表Vote不在会话中?我该怎么做才能更新表Vote

完整堆栈跟踪:

ini_tutors()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in ini_tutors
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3215, in first
    ret = list(self[0:1])
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3007, in __getitem__
    return list(res)
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3317, in __iter__
    return self._execute_and_instances(context)
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3339, in _execute_and_instances
    querycontext, self._connection_from_session, close_with_result=True
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3354, in _get_bind_args
    mapper=self._bind_mapper(), clause=querycontext.statement, **kw
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3332, in _connection_from_session
    conn = self.session.connection(**kw)
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1123, in connection
    execution_options=execution_options,
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1129, in _connection_for_bind
    engine, execution_options
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 407, in _connection_for_bind
    self._assert_active()
  File "/Users/xieling/Documents/GitHub/5505_project/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 294, in _assert_active
    % self._rollback_exception
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.username
[SQL: INSERT INTO user (username, email, password_hash, is_voted) VALUES (?, ?, ?, ?)]
[parameters: ('susan', 'susan@example.com', 'pbkdf2:sha256:150000$CjbmEOm6$02e28253a378d7c2217f98a1b9a96bae58126d2ebd6efe5c12af60eb11328fdb', None)]

1 个答案:

答案 0 :(得分:0)

我通过重新启动VScode解决了这个问题