我有一个User类:
class User(db.Model, UserMixin):
"""
ORM Class: An object that represents a user
"""
__tablename__ = "Users"
id = db.Column('id', db.Integer, primary_key=True)
email = db.Column('email', db.String(128), unique=True)
passwordhash = db.Column('passwordhash', db.String(128))
def __init__(self, email, password):
self.email = email
self.passwordhash = generate_password_hash(password)
logging.info("creating user with email and pw:" + email + " " + password)
当我创建新用户时:
newuser = User(email="test@email.com", password="hunter2")
db.session.add(newuser)
我得到一个KeyError:140736669950912
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 988, in __call__
return self.registry[key]
KeyError: 140736669950912
这个号码来自哪里?我在处理KeyError期间也遇到了另一个错误,即RuntimeError: application not registered on db instance and no applicationbound to current context
答案 0 :(得分:0)
根据current documentation的建议,
而不是手动创建SqlAlchemy()
的实例并将其保存到db
,尝试继承sqlalchemy.ext.declarative.Base
,如下所示:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(DATABASE_URI, echo=False)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
# the following should be moved to your models.py
from sqlalchemy import Column, Integer, String
class User(Base):
"""ORM Class: An object that represents a user
"""
__tablename__ = "Users"
id = Column(Integer)
email = Column(String(128), primary_key=True)
passwordhash = Column(String(128), unique=True)
答案 1 :(得分:0)
检查您的迁移是否最新也可能有所帮助。当我遇到此问题时,在删除现有迁移并重新运行迁移后,该问题已得到解决:
python manage.py db migrate
python manage.py db ugrade