sqlalchemy.orm.exc.UnmappedInstanceError: Class #39;builtins.dict#39; is not mapped(SqlalChemy.orm.ex.UnmappdInstanceError:未映射构建类。)
本文介绍了SqlalChemy.orm.ex.UnmappdInstanceError:未映射构建类。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用SQLAlChemy和棉花糖将新用户插入到数据库中。从API终结点接收user
参数。在create
函数:
db.session.add(new_user)
此时new_user
变量的值为:
{'password': 'string', 'email': 'fave@string', 'username': 'string'}
函数:
def create(user):
uname = user.get('username')
email = user.get('email')
password = user.get ('password')
existing_username = User.query.filter(User.username == uname).one_or_none()
if existing_username is None:
schema = UserSchema()
new_user = schema.load(user, session=db.session)
db.session.add(new_user) <- It fails here
db.session.commit()
return schema.dump(new_user), 201
型号:
class User (db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
profile_picture = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
creation_date = db.Column(db.DateTime(120), nullable=False, default=datetime.utcnow)
updated_date = db.Column(db.DateTime(120), nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User ('{self.username}','{self.email}','{self.profile_picture}') "
class Post (db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime(120), nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post ('{self.title}','{self.date_posted}') "
架构:
class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
sqla_session = db.session
我认为相关的部分控制台错误:
127.0.0.1 - - [14/May/2020 21:33:35] "POST /api/v1/users HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1975, in add
state = attributes.instance_state(instance)
AttributeError: 'dict' object has no attribute '_sa_instance_state'
The above exception was the direct cause of the following exception:
.
.
.
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/connexion/decorators/parameter.py", line 121, in wrapper
return function(**kwargs)
File "/Users/user/development/flask/apis/src/users.py", line 100, in create
db.session.add(new_user)
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1978, in add
exc.UnmappedInstanceError(instance), replace_context=err,
File "/Users/user/.local/share/virtualenvs/apis-JEynsq5i-/Users/user/.pyenv/shims/python/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.dict' is not mapped
我不确定为什么要抛出Class 'builtins.dict' is not mapped
错误。有什么建议吗?
推荐答案
@IljaEverilä谢谢,帮助我解决了这个问题。
我也发现了类似的问题:https://github.com/marshmallow-code/marshmallow/issues/630
建议使用棉花糖-SQL化学。
我使用的是从配置文件创建的棉花糖对象:
config.py:
from flask_marshmallow import Marshmallow
ma = Marshmallow(app)
我的用户架构为:
from .config import db, ma
.
.
.
class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
sqla_session = db.session
并将其更新为:
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, auto_field
class UserSchema(SQLAlchemyAutoSchema):
class Meta:
model = User
include_relationships = True
load_instance = True
如下所示:
https://github.com/marshmallow-code/marshmallow-sqlalchemy#generate-marshmallow-schemas
它现在起作用了。
这篇关于SqlalChemy.orm.ex.UnmappdInstanceError:未映射构建类。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:SqlalChemy.orm.ex.UnmappdInstanceError:未映射构建类。
基础教程推荐
猜你喜欢
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01