Skip to content

Commit

Permalink
Merge pull request #479 from idoshr/mongo_json_parse
Browse files Browse the repository at this point in the history
Added: support for json parse of aggregation cursor
  • Loading branch information
insspb committed Jul 20, 2022
2 parents 2245a86 + 60d41c4 commit fb9e38c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ This project is made by incredible authors:
- fieliapm
- Garito
- Gregg Lind
- Ido Shraga
- icoz
- Jack Stouffer
- Jamar Parris
Expand Down
3 changes: 3 additions & 0 deletions flask_mongoengine/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from flask.json import JSONEncoder
from mongoengine.base import BaseDocument
from mongoengine.queryset import QuerySet
from pymongo.command_cursor import CommandCursor


def _make_encoder(superclass):
Expand All @@ -16,6 +17,8 @@ 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, CommandCursor):
return json_util._json_convert(obj)
elif isinstance(obj, DBRef):
return obj.id
elif isinstance(obj, ObjectId):
Expand Down
27 changes: 27 additions & 0 deletions tests/test_json_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ def setup_endpoints(app, todo):
def index():
return flask.jsonify(result=Todo.objects())

@app.route("/as_pymongo")
def as_pymongo():
return flask.jsonify(result=Todo.objects().as_pymongo())

@app.route("/aggregate")
def aggregate():
return flask.jsonify(
result=Todo.objects().aggregate({"$match": {"title": {"$ne": "lksdjh"}}})
)

@app.route("/add", methods=["POST"])
def add():
form = flask.request.form
Expand Down Expand Up @@ -57,7 +67,24 @@ def test_basic_insert(app):
client = app.test_client()
client.post("/add", data={"title": "First Item", "text": "The text"})
client.post("/add", data={"title": "2nd Item", "text": "The text"})

rv = client.get("/")
result = flask.json.loads(rv.data).get("result")
assert len(result) == 2
for i in result:
assert "title" in i
assert "text" in i

rv = client.get("/as_pymongo")
result = flask.json.loads(rv.data).get("result")
assert len(result) == 2
for i in result:
assert "title" in i
assert "text" in i

rv = client.get("/aggregate")
result = flask.json.loads(rv.data).get("result")
for i in result:
assert "title" in i
assert "text" in i
assert len(result) == 2

0 comments on commit fb9e38c

Please sign in to comment.