python - How can I serialize a MongoDB ObjectId with Marshmallow? -
I am building up and building API over the flask using masamoleo and mongoagine. When I make a call and an ID serial is considered to get the following error:
Writing Error: ObjectId ('54c117322053049ba3ef31f3') is not a JSON serializable I have seen some ways with other libraries to override the way I treat object ID.
class process (db.Document): name = db.StringField (MAX_LENGTH = 255, required = true, unique = true) created_at = db.DateTimeField (default = datetime.datetime.now, required = true) my seri Class process serializer: class meta: field = ("id", "created", "name")
and more View:
class ProcessView (resource): def find (auto, id): process = Process.objects.get_or_404 (id) Return ProcessSerializer (process) .data < / Pre>
When you pass just one code to Meta.fields , then Marshmallow Attempts to select a field type for each attribute. Since it does not know what a ObjectId is, it only sends a serialized dict when you try to dump it on JSON, it does not know that a ObjectId What happens and generate an error, To solve it, you have to tell Marshmall that to use the field for the ID, A can be converted into a string, so a string < Use the / code> field. Marshmaulo Import Schema, Field Class Process Schema (Schema) from: fields.String () Class Meta: Extra = ('created_t', 'name')
Pre> You can also tell Marshmall to use which code to type ObjectId so you do not have to add the area every time.
from the Marshmallow import schema, from the bson import ObjectId fields, Schema.TYPE_MAPPING [ObjectId] = fields.String
Comments
Post a Comment