首页 > 解决方案 > Flask-RESTful API 不会以 json 格式返回字典

问题描述

我正在使用烧瓶-restful api。当我更改debug=Truedebug=False我不接收 json 格式的数据时。这是示例代码:

from flask import Flask, jsonify, Response
from flask_restful import Resource, Api
import json

app = Flask(__name__)

# Create the API
api = Api(app)

@app.route('/')
def index():
    return "HELLO WORLD"


class tests(Resource):

    def get(self):
        #return json.dumps({"A":1, "B":2}, sort_keys=False, indent=4)
        return jsonify({"A":1, "B":2}) 

api.add_resource(tests, '/<string:identifier>')

if __name__ == '__main__':
    app.run(debug=False)

使用 json.dumps(dictionary) 它返回:

"{\n \"A\": 1,\n \"B\": 2\n}"

但我希望:

{
  "A": 1,
  "B": 2
 }

标签: python-3.xapiflask-restful

解决方案


定义的资源是您的问题的原因,因为它要求您将“self”传递给内部的函数。将类定义为对象而不是资源将绕过这一点,同时仍允许您将参数传递给函数,例如 id,如 get_tests_id() 中所示。

from flask import Flask, json
from flask_restful import Api

app = Flask(__name__)

# Create the API
api = Api(app)


@app.route('/')
def index():
    return "HELLO WORLD"


class Tests(object):

    # function to get all tests
    @app.route('/tests', methods=["GET"])
    def get_tests():
        data = {"A": 1, "B": 2}
        return json.dumps(data, sort_keys=False, indent=4), 200

    # function to get tests for the specified id("A" or "B" in this case) 
    @app.route('/tests/<id>', methods=["GET"])
    def get_tests_id(id):
        data = {"A": 1, "B": 2}
        return json.dumps({id: data.get(id)}, sort_keys=False, indent=4), 200


if __name__ == '__main__':
    app.run(debug=False)

假设您在端口 5000 上运行 API 并从主机对其进行测试,则可以使用以下 URL 从 Web 浏览器访问您的数据:

'localhost:5000/tests' - 获取所有测试的 URL

'localhost:5000/tests/A' - 获取 id="A" 测试的 URL

'localhost:5000/tests/B' - 获取 id="B" 测试的 URL


推荐阅读