[英]How to send data via POST or GET in Mod_Python?
使用 JS,我发送 AJAX 发布请求。
$.ajax(
{method:"POST",
url:"https://my/website/send_data.py",
data:JSON.stringify(data),
contentType: 'application/json;charset=UTF-8'
在我的 Apache2 mod_Python 服务器上,我希望我的 python 文件能够访问data
。 我怎样才能做到这一点?
def index(req):
# data = ??
PS:这里是如何重现问题。 创建testjson.html
:
<script type="text/javascript">
xhr = new XMLHttpRequest();
xhr.open("POST", "testjson.py");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function(res) { console.log(xhr.responseText); };
xhr.send(JSON.stringify({'foo': '0', 'bar': '1'}));
</script>
并创建包含以下内容的testjson.py
:
from mod_python import apache
def index(req):
req.content_type = "application/json"
req.write("hello")
data = req.read()
return apache.OK
创建一个.htaccess
包含:
AddHandler mod_python .py
PythonHandler mod_python.publisher
结果如下:
testjson.html:10 POST http://localhost/test_py/testjson.py 501(未实现)
正如 Grisha(mod_python 的作者)在私人通信中指出的,这就是为什么不支持application/json
并输出“HTTP 501 未实现”错误的原因:
https://github.com/grisha/mod_python/blob/master/lib/python/mod_python/util.py#L284
解决方案是修改它,或者使用常规的application/x-www-form-urlencoded
编码,或者使用mod_python.publisher
处理程序以外的其他东西。
mod_python
和PythonHandler mod_python.publisher
示例:
<script type="text/javascript">
var data = JSON.stringify([1, 2, 3, '&=test', "jkl", {'foo': 'bar'}]); // the data to send
xhr = new XMLHttpRequest();
xhr.open("POST", "testjson.py");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(res) { console.log(xhr.responseText); };
xhr.send('data=' + encodeURIComponent(data));
</script>
服务器端:
import json
from mod_python import apache
def index(req):
data = json.loads(req.form['data'])
x = data[-1]['foo']
req.write("value: " + x)
输出:
价值:酒吧
成功!
可以使用request.read()函数读取客户端数据,例如 POST 请求。
来自此处的 Mod Python 文档。
在这里你可以做,例如获取数据
def index(req):
data = req.read()
附加链接: http : //vandermerwe.co.nz/?p=9
正如我所说,从新版本来看,它看起来像是一个配置问题。
首先,尝试设置PythonPath指令。
其次, PythonHandler 应该是你的file ,即:
PythonHandler testjson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.