Python在尝试保存新的JSON文件时导致服务器错误
Python causing server error when trying to save new JSON file
我是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
请注意,这将向系统中的每个用户授予写入权限。
相关文章:
- 咕噜声.js无法读取文件(错误代码:EISDIR)
- 在 ubuntu 14.04 VPS 上执行.js文件错误
- 命令代码jquery文件错误
- XMLHttpRequest无法加载Angular js中的文件错误
- 咕噜声/巴别塔错误:无法写入“dist”文件(错误代码:EISDIR)
- 未捕获的类型错误:对象[对象对象]在文件 y 错误中没有方法“x”
- angularjs + 下载 csv 文件 + 错误: [$injector:unpr] 未知提供程序
- 露天更新文件 - 错误开机自检
- Django ExtJs 6:上传文件错误
- Dropbox放入保护程序本地主机文件错误
- 我的网站在提交时出现文件错误
- php生成的JSON文件错误
- JSON文件错误
- 为什么Chrome开发者工具/控制台不显示javascript文件/错误是动态加载的
- 保存JSON文件错误
- Facebook Javascript表单数据照片上传:需要上传文件错误
- 如何在Node.js中上传文件?错误:无法POST/上载
- 外部javascript文件错误
- 使用jQuery表单插件上传文件-无效文件错误
- Json上传jquery文件错误