Skip to content

Commit

Permalink
Merge pull request #445 from idoshr/master
Browse files Browse the repository at this point in the history
Encode DBRef and ObjectId
  • Loading branch information
insspb committed Jul 1, 2022
2 parents fc2627a + 54ea1e4 commit 9be2d92
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 5 additions & 1 deletion flask_mongoengine/json.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from bson import json_util
from bson import DBRef, ObjectId, json_util
from flask.json import JSONEncoder
from mongoengine.base import BaseDocument
from mongoengine.queryset import QuerySet
Expand All @@ -16,6 +16,10 @@ def default(self, obj):
return json_util._json_convert(obj.to_mongo())
elif isinstance(obj, QuerySet):
return json_util._json_convert(obj.as_pymongo())
elif isinstance(obj, DBRef):
return obj.id
elif isinstance(obj, ObjectId):
return obj.__str__()
return superclass.default(self, obj)

return MongoEngineJSONEncoder
Expand Down
16 changes: 15 additions & 1 deletion tests/test_json_app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import flask
import pytest
from bson import ObjectId
from bson import DBRef, ObjectId


@pytest.fixture(autouse=True)
Expand All @@ -22,6 +22,14 @@ def add():
def show(id):
return flask.jsonify(result=Todo.objects.get_or_404(id=id))

@app.route("/object_id")
def object_id():
return flask.jsonify(result=ObjectId())

@app.route("/dbref")
def dbref():
return flask.jsonify(result=DBRef("Todo", ObjectId()))


def test_with_id(app, todo):
Todo = todo
Expand All @@ -32,6 +40,12 @@ def test_with_id(app, todo):
response = client.post("/add", data={"title": "First Item", "text": "The text"})
assert response.status_code == 200

response = client.get("/dbref")
assert response.status_code == 200

response = client.get("/object_id")
assert response.status_code == 200

response = client.get(f"/show/{Todo.objects.first().id}/")
assert response.status_code == 200

Expand Down

0 comments on commit 9be2d92

Please sign in to comment.