"AttributeError: 'function' object has no attribute 'get'" in SQLAlchemy ORM Object contructor - Flask

"AttributeError: 'function' object has no attribute 'get'" in SQLAlchemy ORM Object contructor - Flask

编辑 发现我的错误!保持问题描述不变,但在下面附加答案。

在我的注册功能中,我想创建一个新用户 object。 我定义了一个 User Table 这样的:

class User(_USERDB.Model, UserMixin):
    """
    User defining Data
    """
    __tablename__ = "users"
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    mail = Column(Text, unique=True, nullable=False)
    pw = Column(Text, nullable=False)
    date_of_creation = Column(DateTime(timezone=True), default=datetime.now)  # the date the user is created
    settings = relationship("UserSettingProfile", back_populates="user", passive_deletes=True)
    admin = Column(Boolean, default=False, nullable=False)
    world_id = Column(Integer, nullable=True)

    def __dict__(self):
        return {
            "id": self.id,
            "mail": self.mail,
            "date_of_creation": self.date_of_creation,
            "admin": self.admin,
            "world_id": self.world_id
        }

如果我现在像其他教程一样使用构造函数(TechWithTim - Flask Bog 教程)

new_user = User(mail=mail, pw=pw_hash, admin=admin)

我从标题中得到错误 "AttributeError: 'function' object has no attribute 'get'"

我已经尝试通过调试器来找出它的来源,但它并不比堆栈跟踪更有帮助。我所做的只是验证堆栈跟踪,是堆栈跟踪(确实不是很有帮助)

Traceback (most recent call last):
  File "E:\project\venv\Lib\site-packages\flask\app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "E:\project\venv\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "E:\project\venv\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "E:\project\venv\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "E:\project\venv\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "E:\project\venv\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "E:\project\web_interface\routes\api_routing.py", line 135, in register
    new_user = User(mail=mail, pw=pw_hash, admin=admin)
  File "<string>", line 4, in __init__
    
  File "E:\project\venv\Lib\site-packages\sqlalchemy\orm\state.py", line 479, in _initialize_instance
    with util.safe_reraise():
  File "E:\project\venv\Lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "E:\project\venv\Lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "E:\project\venv\Lib\site-packages\sqlalchemy\orm\state.py", line 477, in _initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "E:\project\venv\Lib\site-packages\sqlalchemy\orm\decl_base.py", line 1157, in _declarative_constructor
    setattr(self, k, kwargs[k])
  File "E:\project\venv\Lib\site-packages\sqlalchemy\orm\attributes.py", line 459, in __set__
    self.impl.set(
  File "E:\project\venv\Lib\site-packages\sqlalchemy\orm\attributes.py", line 1094, in set
    old = dict_.get(self.key, NO_VALUE)
AttributeError: 'function' object has no attribute 'get'

为了完成,这是我的 api_routing.py 文件:

from flask import Blueprint, request, jsonify
from database import User, UserSettingProfile

@api_routes.route("/register", methods=["POST"])
def register():

    response = {"message": ""}

    try:
        mail = request.values["mail"]
        pw1 = request.values["pw1"]
        pw2 = request.values["pw2"]

    except KeyError as e:
        response["message"] = f"{e=} | Missing argument. Expected: mail, password1, password2"
        return jsonify(response), 400

    admin = False

    pw_hash = hash_pw(pw1)
    print(f"{pw_hash=}\n{mail=}\n{admin=}")
    new_user = User(mail=mail, pw=pw_hash, admin=admin)
    print(new_user)
    new_user_settings = UserSettingProfile(user_id=new_user.id)

    _USERDB.session.add(new_user)
    _USERDB.session.add(new_user_settings)
    _USERDB.session.commit()

    login_user(new_user, remember=True)
    response["message"] = f"{mail=} registered and logged in successfully"
    return jsonify(response), 200

我传递给 User() 构造函数的所有参数均有效且符合预期:

pw_hash='bUpznQzJgw/zLZLGmjBkfOpm.D8iGXf/OsfqRkAVyzcZFM88kdos2'
mail='test_mail'
admin=False

看了其他帖子后,我double-checked: 命名空间中的名称“User”确实映射到我定义的model-class。

回答

失败的原因是__dict__方法。自从删除它后,一切正常。

当然这会引出下一个问题:How to define custom dict functions for those 类

我找不到这个问题的答案,但仍想提供一个解决方案: 定义一个自定义函数,将所需的 obj 作为参数,然后将所需的字段放入字典中。在我看来,这不是最优雅的解决方案,但它确实有效。