我有一个 api,我正在尝试使用 Flask-Pymongo 存储/发布用户对象。
但是,我收到以下错误
文件“/home/kay/.local/share/virtualenvs/server-iT4jZt3h/lib/python3.7/site-packages/flask/json/i│ nit .py”,第 321 行,在 jsonify
│转储(数据,缩进=indent, separators=separators) + '\n', │ 文件 "/home/kay/.local/share/virtualenvs/server-iT4jZt3h/lib/python3.7/site-packages/flask/json/ i│ nit . py”,第 179 行,转储中
│ rv = _json.dumps(obj, **kwargs) │ 文件“/usr/lib/python3.7/json/init .py ”,第 238 行,转储中
│ **kw) .encode(obj) │ 文件“/usr/lib/python3.7/json/encoder.py”,第 201 行,在编码中
│ chunks = list(chunks) │ 文件“/usr/lib/python3.7/json/encoder.py”,第 438 行,在 _iterencode 中 │ o = _default(o) │ 文件“/home/kay/link/server/ src/run.py",第 18 行,默认
│ return json.JSONEncoder.default(self, o) │ 文件 "/usr/lib/python3.7/json/encoder.py",第 179 行,默认
│ raise TypeError( f'Object of type {o.class.name } ' │ TypeError: Object of InsertOneResult is not JSON serializable
应用程序/用户/resource.py
from flask_restful import Resource
from flask import jsonify, request
from .repository import UsersRepository
from db import mongo
class UsersResource(Resource):
def __init__(self):
self.repository = UsersRepository()
def get(self):
data = {"Users": "Resource"}
res = data, 200
return res
def post(self):
req = request.get_json()
user = {
"email": req.get("email"),
"password": req.get("password")
}
result = mongo.db.users.insert_one(user)
return jsonify(result)
运行.py
from flask import Flask
from app import api_bp
from db import mongo
from bson.objectid import ObjectId
import json
import datetime
import os
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
if isinstance(o, set):
return list(o)
if isinstance(o, datetime.datetime):
return str(o)
return json.JSONEncoder.default(self, o)
def create_app(config_filename):
app = Flask(__name__)
app.config.from_object(config_filename)
app.register_blueprint(api_bp, url_prefix='/api')
mongo.init_app(app)
app.json_encoder = JSONEncoder
return app
# def logger():
# def database():
if __name__ == "__main__":
app = create_app("config")
app.run(host='0.0.0.0', port=8080, debug=True)