title: how to encode POST data using python's urllib
body: <p>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</p>
  
  <pre><code>import urllib2
  import urllib
  
  url = "http://localhost:8000/minion/serve"
  request = urllib2.Request(url)
  response = urllib2.urlopen(request)
  html = response.read()
  print html
  </code></pre>
  
  <p>However if I change it to</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I get <code>urllib2.HTTPError: HTTP Error 500: INTERNAL SERVER ERROR</code>.  Am I doing something wrong here?  Here are the tutorials I was trying to follow, <a href="http://techmalt.com/?p=212" rel="nofollow">http://techmalt.com/?p=212</a> <a href="http://docs.python.org/2/howto/urllib2.html" rel="nofollow">http://docs.python.org/2/howto/urllib2.html</a>. </p>
  
  <p>EDIT: tried to make the following change as per That1Guy's suggestion (other lines left the same)</p>
  
  <pre><code>request =  urllib2.Request(url, data)
  response = urllib2.urlopen(request, data)
  </code></pre>
  
  <p>This returned the same error message as before.</p>
  
  <p>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:</p>
  
  <pre><code>def serve(request):
      return HttpResponse("You've been served!")
  </code></pre>
  
  <p>As you can see, it's very straight forward.</p>
  
  <p>EDIT: Tested to see if Internal Error might be caused by missing csrf token, but csrf_exempt decorator failed to resolve error.</p>