如何通过 POST 或 GET in Mod_Python 发送数据?

How to send data via POST or GET in Mod_Python?

使用 JS,我发送 AJAX post 请求。

 $.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 (Not Implemented)

来自Mod_python docs

Client data, such as POST requests, can be read by using the request.read() function.

来自 Mod Python 文档 here

这里可以做,比如获取数据

def index(req):
    data = req.read()

附加链接:http://vandermerwe.co.nz/?p=9

正如我所说,从新版本来看,它看起来像是配置问题。

首先,尝试设置 PythonPath 指令。

其次,PythonHandler 应该是您的 file,即:

PythonHandler testjson

正如 Grisha(mod_python 的作者)在私人交流中所指出的,这是不支持 application/json 并输出 "HTTP 501 Not implemented" 错误的原因:

https://github.com/grisha/mod_python/blob/master/lib/python/mod_python/util.py#L284

解决方案是修改它,或者使用常规 application/x-www-form-urlencoded 编码,或者使用 mod_python.publisher 处理程序以外的其他东西。

mod_pythonPythonHandler 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)

输出:

value: bar

成功!