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)
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!
From Mod_python docs:
Client data, such as POST requests, can be read by using the request.read() function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With