我正在使用 Python Flask 创建服务器。我想将 application/json
发送回客户端(我的客户需要这个)。当我使用 json.dumps() 时,它会发回文本。
(如果你想知道,如果我使用 jsonify() 而不是 json.dumps(),我确实得到了 application/json,但是这个函数似乎对某些数据有问题(如果我在这里没有得到解决方案,我会进一步研究 jsonify))。
服务器............
import json
from flask import Flask, render_template, url_for, current_app, request, jsonify
app = Flask(__name__)
@app.route("/<arg1>")
def route1(arg1):
dict1 = {"prop1": "p1", "prop2": "p2"}
#return jsonify(dict1) # this sends 'application/json'
return json.dumps(dict1) # this sends ' text/html; charset=utf-8'
app.run(host="0.0.0.0", port=8080, debug=True)
测试客户端(实际客户端由客户提供)......
import pycurl
import cStringIO
SERVER_URL = "http://192.168.47.133:8080"
buf = cStringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, SERVER_URL + '/index.html?city=perth')
c.setopt(c.HTTPHEADER, ['Accept:application/json'])
c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.VERBOSE, True)
c.perform()
buf1 = buf.getvalue()
buf.close()
print(buf1)
最佳答案
像这样改变它:
from flask import Response
@app.route("/<arg1>")
def route1(arg1):
dict1 = {"prop1": "p1", "prop2": "p2"}
return Response(json.dumps(dict1), mimetype='application/json')
关于json - 使用 json.dumps 让 Python Flask 返回 application/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666805/