python - sqlalchemy postgres : AttributeError: can't set attribute

标签 python python-3.x postgresql sqlalchemy flask-sqlalchemy

当用 sqlalchemy 初始化我的 postgres 数据库时,我得到一个 AttributeError: can't set attribute 错误:

Traceback (most recent call last):
  File "manage.py", line 567, in <module>
    manager.run()
  File "/usr/local/lib/python3.6/site-packages/flask_script/__init__.py", line 417, in run
    result = self.handle(argv[0], argv[1:])
  File "/usr/local/lib/python3.6/site-packages/flask_script/__init__.py", line 386, in handle
    res = handle(*args, **config)
  File "/usr/local/lib/python3.6/site-packages/flask_script/commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "manage.py", line 26, in initdb
    password="passwo",
  File "<string>", line 4, in __init__
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 417, in _initialize_instance
    manager.dispatch.init_failure(self, args, kwargs)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
    compat.reraise(exc_type, exc_value, exc_tb)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 414, in _initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 700, in _declarative_constructor
    setattr(self, k, kwargs[k])
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 873, in __set__
    raise AttributeError("can't set attribute") AttributeError: can't set attribute

表格定义如下:

class User(db.Model, UserMixin):
    """
    A user who has an account on the website.
    """

    __tablename__ = 'user'

    id = db.Column(db.Integer,
                   primary_key=True,
                   nullable=False,
                   unique=True,
                   autoincrement=True)
    first_name = db.Column(db.String)
    last_name = db.Column(db.String)
    phone = db.Column(db.String)
    email = db.Column(db.String, unique=True)
    photo = db.Column(db.String, default="No Picture")
    _password = db.Column(db.Binary(60))

并像这样初始化:

def initdb():
    ''' Create the SQL database. '''
    db.create_all()
    print(colored('The SQL database has been created', 'green'))

    user2 = models.User(
        first_name="Jane",
        last_name="Doe",
        phone="123",
        email="test@test.test",
        password="passwo",
    )
    db.session.add(user2)

如何正确初始化数据库?

更新 1: 我将我的 SQLAlchemy 从 1.2.5 降级到 1.1.15(按照 https://github.com/puckel/docker-airflow/issues/160 中的建议,错误消失了。有没有办法避免 1.2.5 中的错误?

最佳答案

可能的问题是您正在使用密码和自定义 setter 的混合属性,这在 Flask 示例中很常见,看起来像这样:

Class User(db.Model)
...
    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def _set_password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext).decode('utf-8')

为了与 Python 属性保持一致,SQLAlchemy 决定禁止使用调用不同于它们所影响的混合属性名称的函数。所以上面现在需要是:

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext).decode('utf-8')

参见 https://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html了解更多详情。

关于python - sqlalchemy postgres : AttributeError: can't set attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49240581/

相关文章:

Python 错误 : global name Xis not defined

python - 通过python代码附加JSON文件

python - tf.Graph 中的修改改变了我的 NN 权重初始化

plugins - 基于Python的浏览器插件?

sql - 在 postgresql 上执行服务生成器生成的 sql 文件

javascript - 如何查询与 Knex.js 的关系?

python - Numpy,如何使用 bool 切片获取子矩阵

python - 在定义的函数中识别/接受的非全局变量

python - 如何使用 PyPDF2 将 *.png 图像文件插入 .pdf 文件

postgresql - 从标准输入复制在 liquibase 中不起作用