python-3.x - Flask-RESTful API 不会以 json 格式返回字典
问题描述
我正在使用烧瓶-restful api。当我更改debug=True
为debug=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
}
解决方案
定义的资源是您的问题的原因,因为它要求您将“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
推荐阅读
- c# - 获取动词没有要求采取正确的行动
- liferay - Liferay 将系统捆绑包保存在哪里?
- sql - 在 Amazon Redshift 的列中获取特定值之后的下一条记录
- java - 有什么方法可以获取触发 azure blob 触发器的文件内容?
- azure - 在 Graph 中检索照片时从 Microsoft 获取“AuthenticationError”
- python - 如何从单词边界中排除逗号
- celery - 在客户端/生产者上记录 Celery
- git - 删除 Git 提交
- python - “设置全局变量”或“设置套件变量”关键字在机器人框架中不起作用
- python - 如何根据函数输出写入单独的列