0

晚上好,我在使用 flask-restful 时遇到了身份验证问题,当我启动与数据库的连接时出现此错误:“ TypeError:ObjectId 类型的对象不是 JSON 可序列化//Werkzeug Debugger

文件“C:\Users\xxxx\AppData\Local\Programs\Python\Python39\Lib\json\encoder.py”,第 179 行,默认引发 TypeError (f'Object of type {o .__ class .name__ } ' TypeError:ObjectId 类型的对象不是 JSON 可序列化的

我遵循了官方文档:https ://pythonhosted.org/Flask-JWT/ 这是我的代码:customer.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)  
from flask import jsonify, request, make_response
from flask_restful import Resource
from Models.Customer import Customer
from config.security import auth, identity
from flask_jwt import JWT, jwt_required
from config.app import app

app.config['SECRET_KEY'] = 'super-secret'
app.config.update(
     JWT=JWT(app, auth, identity)
)

class CustomerController(Resource): 
    @jwt_required()
    def get(self, _id):
        if request.method == 'GET':     
            customer_obj = Customer.objects(_id=_id).first()
            return make_response(jsonify(customer_obj), 200)

感谢您的帮助

4

0 回答 0