Skip to content

Commit 5f20261

Browse files
committed
Encode DBRef and ObjectId
1 parent 8cd926c commit 5f20261

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

flask_mongoengine/json.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from bson import json_util
1+
from bson import json_util, DBRef, ObjectId
22
from flask.json import JSONEncoder
33
from mongoengine.base import BaseDocument
44
from mongoengine.queryset import QuerySet
@@ -16,6 +16,10 @@ def default(self, obj):
1616
return json_util._json_convert(obj.to_mongo())
1717
elif isinstance(obj, QuerySet):
1818
return json_util._json_convert(obj.as_pymongo())
19+
elif isinstance(obj, DBRef):
20+
return obj.id
21+
elif isinstance(obj, ObjectId):
22+
return obj.__str__()
1923
return superclass.default(self, obj)
2024

2125
return MongoEngineJSONEncoder

tests/test_json_app.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import flask
22
import pytest
3-
from bson import ObjectId
3+
from bson import ObjectId, DBRef
44

55

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

25+
@app.route("/object_id")
26+
def object_id():
27+
return flask.jsonify(result=ObjectId())
28+
29+
@app.route("/dbref")
30+
def dbref():
31+
return flask.jsonify(result=DBRef('Todo', ObjectId()))
32+
2533

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

43+
response = client.get("/dbref")
44+
assert response.status_code == 200
45+
46+
response = client.get("/object_id")
47+
assert response.status_code == 200
48+
3549
response = client.get("/show/%s/" % Todo.objects.first().id)
3650
assert response.status_code == 200
3751

0 commit comments

Comments
 (0)