Background:
I'm building a basic flask app, that will allow me to return a Collection from a Atlas Compass Cluster and then use the Collection data to create an HTML container to display the data and create some D3 charts.
Issue:
I've created two @app.route
, to allow me to visualize how both json.dump
and flask.jsonify
return data, before I decide which to use
Unfortunately whilst my json.dump
route returns the data (via an index.html page), my jsonify doesn't seem to work.. I get the following error returned in my Terminal
Error:TypeError: jsonify() behavior undefined when passed both args and kwargs
Code:
Here is my code, which shows both @app.route
import flask
from flask import Flask, jsonify
import pymongo
from pymongo import MongoClient
from bson import ObjectId, json_util
import json
cluster = pymongo.MongoClient("mongodb+srv://group2:<PASSWORD>@cluster0.mpjcg.mongodb.net/<dbname>?retryWrites=true&w=majority")
db = cluster["simply_recipe"]
collection = db["recipes_collection"]
app = Flask(__name__)
@app.route("/recipes", methods=["GET"])
def get_recipes():
all_recipes = list(collection.find({}))
return json.dumps(all_recipes, default=json_util.default)
@app.route("/recipes_jsonify", methods=["GET"])
def get_recipes_jsonify():
all_recipes = list(collection.find({}))
return flask.jsonify(all_recipes, default=json_util.default)
I'm a complete beginner with Flask, so no doubt I have missed something obvious, can anyone help?
I also faced the same issue; i was able to fix it by using
data=
Keyword arguments: Treated as a dict of values. jsonify(data=data, errors=errors) is the same as jsonify({"data": data, "errors": errors}). see below ..
@app.route("/recipes_jsonify", methods=["GET"])
def get_recipes_jsonify():
all_recipes = list(collection.find({}))
return flask.jsonify(data=all_recipes, default=json_util.default)