【发布时间】:2014-10-29 06:45:13
【问题描述】:
我正在使用 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)
【问题讨论】:
-
您能否具体说明
jsonify存在哪些数据问题? (我正在为您的问题寻找类似的解决方案)
标签: json python-2.7 flask