简体   繁体   English

Flask-RESTful API不会以json格式返回字典

[英]Flask-RESTful API does not return a dictionary as a json format

I am using flask-restful api. 我正在使用烧瓶式API。 When I change debug=True to debug=False I don't receive data as a json format. 当我将debug=True更改为debug=False我没有收到json格式的数据。 This is the example code: 这是示例代码:

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)

with json.dumps(dictionary) it returns: 使用json.dumps(dictionary)返回:

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

but I expect: 但我期望:

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

The defined resource is the cause of your issue since it requires that you pass "self" to the functions inside. 定义的资源是造成问题的原因,因为它要求您将“自我”传递给内部函数。 Defining the class as an object instead of a resource will circumvent this while still allowing you to pass arguments to the function, such as id, as seen in get_tests_id(). 将类定义为对象而不是资源将避免这种情况,同时仍允许您将参数传递给函数,例如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)

Assuming you are running the API on port 5000 and testing it from the host, the following URLs can be used to access your data from a web browser: 假设您正在端口5000上运行API并从主机对其进行测试,则可以使用以下URL从Web浏览器访问数据:

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

'localhost:5000/tests/A' - URL to get tests with id="A" 'localhost:5000 / tests / A'-用于获取ID =“ A”的测试的URL

'localhost:5000/tests/B' - URL to get tests with id="B" 'localhost:5000 / tests / B'-用于获取ID =“ B”的测试的URL

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

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