python - 我正在编写的 Python REST 服务器中的 json 响应问题

标签 python ajax json

为了我自己的教育,我正在创建一个简单的守护进程,它将充当 REST 服务器,监听套接字 9000。对于我的第一个测试,我尝试进行 REST 调用,只需在 http://localhost:9000/getsettings.json 上执行 GET 即可。 .

我破解的简单服务器可以正常接收请求,但我认为它发送的响应有问题。我正在尝试以 JSON 形式发送响应。服务器套接字的代码如下。下面是我用来发出 JSON 请求的 jQuery 代码。 Python 服务器中的 print 语句确实以 JSON 格式打印一组有效的设置。页面加载时,Javascript 中的警报都不会被调用。有什么想法吗?


Python:
    def socketThread(self):
        while 1:
            sock, address = self.serverSocket.accept()
            fs = sock.makefile()
            line = fs.readline();
            if line.startswith('GET /settings.json'):
                sock.sendall("HTTP/1.0 200 OK\r\n")
                sock.sendall("Content-Type: application/json\r\n")
                settings = json.dumps(self.currentSettings) #, indent=4
                sock.sendall("Content-Length: " + str(len(settings)) + '\r\n\r\n')
                sock.sendall(settings)
                print settings
                sock.close()<p></p>

<p>Javascript:
$(document).ready(function() {
    $.ajax({
        url: 'http://localhost:8080/settings.json',
        cache: false,
        success: function(json){
            alert('json success ' + json);
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
        }
    });
});
</p>

最佳答案

在发送内容之前,您需要返回 200 OK HTTP 响应和空行。

您可能还需要一些 HTTP header (Content-type 是一个明显的 header )。

但是,我建议使用 Python 的众多 HTTP 库之一,而不是自己实现协议(protocol)。

关于python - 我正在编写的 Python REST 服务器中的 json 响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4294185/

相关文章:

php - 从 Rest API 获取 JSON 数据

python - django View 流测试

python - 从 cStringIO 对象创建 Python array.array 对象

java - 如何将 'sub-rows' 插入 Wicket 数据表

jquery - 将数组的结果相加即可得到总计

javascript - 如何使用 javascript 和 json 查找组的所有叶子

python - 使用 python 和 matplotlib 绘制 Excel 工作表?

python - 如何在 pandas 数据帧上执行 groupby 而不丢失其他列?

jquery - Django Jquery 可排序 - 如何访问 POST 数据

javascript - 使用 jQuery 根据国家和州填充州和城市下拉菜单