1

I am trying to send JSON data to my django web app using python urllib but with no luck. This is my code;

Python application:

url = "http://127.0.0.1:8000/web_app"
values = {'name':'Paul','age':12}
jdata = {'data':values}
data = urllib.urlencode(values)
req = urllib2.Request(url, data, {'Content-Type':'application/json'})
try:
   resp = urllib2.urlopen(req)
   the_result = resp.read()
except urllib2.HTTPError, e:
   return "Reques Failed!"

My Django Web App:

@csrf_exempt
def web_app(request):
     print "In My webapp"   # This never get printed!
     data = request.POST['data']
     return HttpResponse("Thankyou...")

The request seems not to be hitting the Django web_app function, because the first print in the function is not executed!

Added: note if i remove the data from the request in the urllib2.request then everything works as expected!!

What am i missing?

1
  • 2
    can you access the page in a browser? Commented May 18, 2012 at 14:17

1 Answer 1

2

What's your urlconf look like? If it looks like '^web_app/$' and APPEND_SLASH=True in settings, which is default, you need to use "http://127.0.0.1:8000/web_app/" (note the suffix slash). Or else Django would try to redirect /web_app to /web_app/ if there is no matching, then complains about redirecting a POST request.

Also, its meaningless to set 'Content-Type':'application/json' for HTTP request, you could set this and break the requirement of urllib2 by passing it a JSON-dumped string; but then you should parse request.body by yourself instead of using request.POST. application/json is normally for specifying the Content-Type of response.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, i also had a bad malformed urlconf pattern, it was like this initially url(r'$', 'myapp.views.home') without the "^" in front of the $ sign. I changed it to look like r'^$' and added the suffix slash. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.