简体   繁体   English

在 Flask 应用程序中返回 flash.jsonify() 时出错

[英]Error when returning flash.jsonify() in Flask App

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.我正在构建一个基本的 flask 应用程序,它将允许我从 Atlas Compass 集群返回一个集合,然后使用集合数据创建一个 HTML 容器来显示数据创建一些 D3 图表。

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我创建了两个@app.route ,让我在决定使用哪个之前可视化json.dumpflask.jsonify如何返回数据

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不幸的是,虽然我的json.dump路由返回数据(通过 index.html 页面),但我的 jsonify 似乎不起作用。我在终端中返回以下错误

Error:错误:
TypeError: jsonify() behavior undefined when passed both args and kwargs

Code:代码:
Here is my code, which shows both @app.route这是我的代码,它同时显示了@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?我是 Flask 的完整初学者,所以毫无疑问我错过了一些明显的东西,有人可以帮忙吗?

here have a look at this example, which explaines how jsonify can handle your data:这里看看这个例子,它解释了 jsonify 如何处理你的数据:

 from flask import jsonify

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(username=g.user.username,
                   email=g.user.email,
                   id=g.user.id)

Output: Output:

{
"username": "admin",
"email": "admin@localhost",
"id": 42
}

Source: https://www.kite.com/python/docs/flask.jsonify来源: https://www.kite.com/python/docs/flask.jsonify

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM