0

我有一个无法解决的错误。这是我在使用邮递员进行身份验证时遇到的错误:TypeError: ObjectId 类型的对象不是 JSON 可序列化 // Werkzeug 调试器 文件“C:\Users\Amoungui\AppData\Local\Programs\Python\Python39\Lib\json\encoder .py",第 179 行,默认 raise TypeError( f'Object of type {o.class .name }' TypeError: ObjectId类型的对象不是 JSON 可序列化的

这是我的代码,我遵循了官方文档,但是在这不起作用我不明白。这是文档的链接:https ://pythonhosted.org/Flask-JWT/

客户.py

from flask import jsonify, make_response
from config.mongoose import db
import bson 

class Customer(db.Document):
    _id = db.ObjectIdField(default=bson.ObjectId, primary_key=True) #bson.ObjectId
    tel = db.StringField()
    password = db.StringField()
    
    def to_json(self):
        return {
            "_id": self._id,
            "tel": self.tel,
            "password": self.password,
        }
     
    def findAll(self):
        users = []
        for user in self.objects:
            users.append(user)
            
        return users

服务.py

from Models.Customer import Customer
from werkzeug.security import safe_str_cmp

find_by_username = {u.tel:u for u in Customer.objects}

find_by_id = {u._id: u for u in Customer.objects}

def auth(username, password):
    user = find_by_username.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user
    
def identity(payload):
    _id = payload['identity']
    return find_by_id.get(_id)  

感谢您的帮助

4

2 回答 2

0

错误消息表明它与序列化有关bson.ObjectId。您是否尝试过以下建议的解决方案:type error objectid

于 2021-09-11T08:56:48.410 回答
0

我像这样更改客户类别

from flask import jsonify, make_response
from config.mongoose import db
import bson 

class Customer(db.Document):
    _id = db.ObjectIdField() #bson.ObjectId
    tel = db.StringField()
    password = db.StringField()
    
    def to_json(self):
        return {
            "_id": self._id,
            "tel": self.tel,
            "password": self.password,
        }
     
    def findAll(self):
        users = []
        for user in self.objects:
            users.append(user)
            
        return users

我有新的错误: identity = getattr(identity, 'id') or identity['id'] File "C:\Users\Amoungui\AppData\Local\Programs\Python\Python39\Lib\site-packages\mongoengine\ base\document.py",第 250 行,在getitem 中引发KeyError
(name) KeyError: 'id'

于 2021-09-11T19:06:31.557 回答