Question

I try to access to a JSON object, sent from JS-jquery with $.post to a Django script,

I tried a combination on many things I saw on Stackoverflow, but I cant make it work :

On the .js side :

$("#submitbtn").click(function() {
    var payload = {"name":"Richard","age":"19"};
    $("#console").html("Sending...");
    $.post("/central/python/mongo_brief_write.py",{'data': JSON.stringify(payload)},
                                           function(ret){alert(ret);});
    $("#console").html("Sent.");
});

and the content of my script named mongo_brief_write.py is :

#!/usr/bin/env python
import pymongo
from pymongo import Connection
from django.utils import simplejson as json

def save_events_json(request):
    t = request.raw_post_data
    return t

con = Connection("mongodb://xxx.xxx.xxx.xxx/")
db = con.central
collection = db.brief
test = {"name":"robert","age":"18"}
post_id = collection.insert(t)

def index(req):
    s= "Done"
return s

If I press the submit button, I have the "Done" alert displayed correctly, but nothing in my collection in my mongoDB.

If I replace t by test in

post_id = collection.insert(test)

I have the done alert too and my object is created in my mongo DB collection.

Where is my mistake ? in my POST request ? I work under Apache and I use modpython.

No correct solution

OTHER TIPS

Looks like its happens because of python namespace rules. If you define variable in function:

>>>def random_func(input):
       t = input
       return t
>>>t
Traceback (most recent call last): File "<input>", line 1, in <module> 
NameError: name 't' is not defined

Its won't be global variable. So, what you need to do is too ways: first, put code with base manipulation in function save_events_json:

def save_events_json(request):
    t = request.raw_post_data
    con = Connection("mongodb://xxx.xxx.xxx.xxx/")
    db = con.central
    collection = db.brief
    test = {"name":"robert","age":"18"}
    post_id = collection.insert(t)
    from django.http import HttpResponse
    return HttpResponse(content=t)

or set the variable "t" global:

def save_events_json(request):
    global t
    t = request.raw_post_data
    return t 

Dear @Kyrylo Perevozchikov, I've updated my code :

import pymongo
from pymongo import Connection
from django.utils import simplejson as json
from django.http import HttpResponse,HttpRequest
request = HttpRequest()
if request.method == 'POST':
    def index(request):
        global t
        t = request.raw_post_data                          
  post_id=Connection("mongodb://xxx.xxx.xxx.xxx/").central.brief.insert(t)
        return HttpResponse(content=t)
else:
    def index(req):
        s="Not A POST Request"
        return s

When I click on the jquery button I have the "Not A POST Request"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top