"属性错误:'函数'对象在 SQLAlchemy ORM 对象构造器中没有属性'get'" - 烧瓶



EDIT 发现我的错误!保留问题描述,但在下面附上答案

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

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:projectvenvLibsite-packagesflaskapp.py", line 2091, in __call__
return self.wsgi_app(environ, start_response)
File "E:projectvenvLibsite-packagesflaskapp.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "E:projectvenvLibsite-packagesflaskapp.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "E:projectvenvLibsite-packagesflaskapp.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "E:projectvenvLibsite-packagesflaskapp.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "E:projectvenvLibsite-packagesflaskapp.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "E:projectweb_interfaceroutesapi_routing.py", line 135, in register
new_user = User(mail=mail, pw=pw_hash, admin=admin)
File "<string>", line 4, in __init__

File "E:projectvenvLibsite-packagessqlalchemyormstate.py", line 479, in _initialize_instance
with util.safe_reraise():
File "E:projectvenvLibsite-packagessqlalchemyutillanghelpers.py", line 70, in __exit__
compat.raise_(
File "E:projectvenvLibsite-packagessqlalchemyutilcompat.py", line 207, in raise_
raise exception
File "E:projectvenvLibsite-packagessqlalchemyormstate.py", line 477, in _initialize_instance
return manager.original_init(*mixed[1:], **kwargs)
File "E:projectvenvLibsite-packagessqlalchemyormdecl_base.py", line 1157, in _declarative_constructor
setattr(self, k, kwargs[k])
File "E:projectvenvLibsite-packagessqlalchemyormattributes.py", line 459, in __set__
self.impl.set(
File "E:projectvenvLibsite-packagessqlalchemyormattributes.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='$2b$14$6UpznQzJgw/zLZLGmjBkfOpm.D8iGXf/OsfqRkAVyzcZFM88kdos2'
mail='test_mail'
admin=False

看了其他帖子后,我仔细检查了一下:名称";用户";在名称空间中确实映射到我定义的模型类。

回答

它失败的原因要归功于__dict__方法。自从拆除后,一切都很好。

当然,这引出了下一个问题:如何为这些类定义自定义dict函数

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

我删除了__dict__,并创建了get_dict(self),以使我的dict在没有构造函数的情况下通过对象。

最新更新