Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data via POST or GET in Mod_Python?

With JS, i send a AJAX post request.

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

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

def index(req):
    # data = ??

PS: here is how to reproduce the problem. Create 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>

and create testjson.py containing:

from mod_python import apache 

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

Create a .htaccess containing:

AddHandler mod_python .py
PythonHandler mod_python.publisher

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)

enter image description here

like image 438
Mitchell van Zuylen Avatar asked Apr 10 '17 14:04

Mitchell van Zuylen


2 Answers

As pointed by Grisha (mod_python's author) in a private communication, here is the reason why application/json is not supported and outputs a "HTTP 501 Not implemented" error:

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

The solution is either to modify this, or to use a regular application/x-www-form-urlencoded encoding, or to use something else than the mod_python.publisher handler.

Example with mod_python and 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>

Server-side:

import json
from mod_python import apache 

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

Output:

value: bar

Success!

like image 104
Basj Avatar answered Oct 20 '22 12:10

Basj


From Mod_python docs:

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

like image 20
A K Avatar answered Oct 20 '22 11:10

A K