Python在尝试保存新的JSON文件时导致服务器错误

Python causing server error when trying to save new JSON file

本文关键字:文件 错误 服务器 JSON 保存 Python      更新时间:2023-09-26

我是Python的新手,所以如果有任何明显的错误,请告诉我。

我创建了一个使用Ajax的简单网页,读取服务器的XML响应,然后将其显示在页面上。我使用一个python脚本来发送XML响应,它是从JSON文件构建的,并且工作得很好。

但是,当我在发送XML响应之前向Python脚本中添加一些修改JSON的代码时,就会出现问题。

以下是导致问题的代码:

with open("../../../var/www/data.json", "r+") as jsonFile:
    data = json.load(jsonFile)
    data[0]["A"] = "2"
    jsonFile.seek(0)  # rewind
    jsonFile.write(json.dumps(data))
    jsonFile.truncate()

当这段代码被放入我的python文件中时,当我的Ajax发送POST请求时,我在浏览器控制台中收到了这个错误:加载资源失败:服务器响应状态为500(内部服务器错误)

但有趣的是,尽管它阻止了我的服务器正确响应,但它确实正确地更新了我的JSON文件。

为什么写入我的JSON文件会导致我的服务器不响应我的POST请求?

这是我的Javascript函数,它发送post请求:

function sendAjax(){
    sendingAjax = true;
    console.log("sending ajax...");
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', "/cgi-bin/xmlTest.py", true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200) {
             if (self.xmlHttpReq.responseXML != null) {
                console.log("server responded with 4!");
                document.getElementById("paragraph").innerHTML = self.xmlHttpReq.responseXML.getElementsByTagName('data')[0].childNodes[0].nodeValue;
                sendingAjax = false;
            }
        }
    }
    self.xmlHttpReq.send();
}

下面是Python脚本:

#!/usr/bin/env python
import cgi
import cgitb
import json

#this worked to open the json file, rewrite it, and then open it again for reading but it needs to be commented out for server to respond properly
with open("../../../var/www/data.json", "r+") as jsonFile:
    data = json.load(jsonFile)
    data[0]["A"] = "2"
    jsonFile.seek(0)  # rewind
    jsonFile.write(json.dumps(data))
    jsonFile.truncate()
newJsonFile = open("../../../var/www/data.json", "r")
newData = json.load(newJsonFile)
newJsonFile.close()
cgitb.enable()

print "Content-Type: text/xml"     
print # blank line, end of headers
print "<?xml version='1.0' encoding='UTF-8' ?><inputs><data>"+newData[0]["A"]+"</data></inputs>"

知道为什么这段代码会导致我的服务器发送500错误代码吗?

附言-我正在使用树莓派2作为我的服务器。

好的,我们在注释部分一起发现了这个bug。RP是一个linux系统,我认为权限错误可以用chmod解决。以拥有apache进程的用户身份登录shell并更改权限OR只需以更简单的方式执行即可:从cd/www/目录并运行以下命令:

cd /var/www
sudo chmod a+w data.json

请注意,这将向系统中的每个用户授予写入权限。