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

Mit*_*len 8 python apache post mod-python

使用 JS,我发送一个 AJAX 发布请求。

 $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'
Run Code Online (Sandbox Code Playgroud)

在我的 Apache2 mod_Python 服务器上,我希望我的 python 文件能够访问data. 我怎样才能做到这一点?

def index(req):
    # data = ??
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

并创建testjson.py包含:

from mod_python import apache 

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK
Run Code Online (Sandbox Code Playgroud)

创建一个.htaccess包含:

AddHandler mod_python .py
PythonHandler mod_python.publisher
Run Code Online (Sandbox Code Playgroud)

结果如下:

testjson.html:10 POST http://localhost/test_py/testjson.py 501(未实现)

在此处输入图片说明

Bas*_*asj 3

正如 Grisha(mod_python 的作者)在私人通信中所指出的,原因如下application/json正如 Grisha(mod_python 的作者)在私人通信中所指出的,这是不支持并输出“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_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>
Run Code Online (Sandbox Code Playgroud)

服务器端:

import json
from mod_python import apache 

def index(req):
    data = json.loads(req.form['data'])
    x = data[-1]['foo']
    req.write("value: " + x)
Run Code Online (Sandbox Code Playgroud)

输出:

值: 酒吧

成功!