Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to encode POST data using python's urllib

I'm trying to connect to my Django server using a client side python script. Right now I'm just trying to connect to a view and retrieve the HttpResponse. The following works fine

import urllib2
import urllib

url = "http://localhost:8000/minion/serve"
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read()
print html

However if I change it to

import urllib2
import urllib

url = "http://localhost:8000/minion/serve"
values = {'name': 'Bob'}
data = urllib.urlencode(values)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
html = response.read()
print html

I get urllib2.HTTPError: HTTP Error 500: INTERNAL SERVER ERROR. Am I doing something wrong here? Here are the tutorials I was trying to follow, http://techmalt.com/?p=212 http://docs.python.org/2/howto/urllib2.html.

EDIT: tried to make the following change as per That1Guy's suggestion (other lines left the same)

request =  urllib2.Request(url, data)
response = urllib2.urlopen(request, data)

This returned the same error message as before.

EDIT: It seems to work if I change the page I'm viewing so the error isn't in the client side script. So in light of that revelation, here's the server side view that's being accessed:

def serve(request):
    return HttpResponse("You've been served!")

As you can see, it's very straight forward.

EDIT: Tested to see if Internal Error might be caused by missing csrf token, but csrf_exempt decorator failed to resolve error.

like image 998
avorum Avatar asked Jan 24 '26 02:01

avorum


1 Answers

Finally figured it out with this. How to POST dictionary from python script to django url?

Turns out my url was missing a trailing slash. It's the little things that always get you I guess.

like image 167
avorum Avatar answered Jan 25 '26 14:01

avorum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!