Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python URLLib / URLLib2 POST

I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data:

data = urllib.urlencode({'q': 'Status'}) u = urllib2.urlopen('http://myserver/inout-tracker', data) for line in u.readlines():   print line 

Nothing special going on there. The problem I'm having is that, based on how I read the docs, this should perform a Post Request because I've provided the data parameter and that's not happening. I have this code in the index for that url:

if (!isset($_POST['q'])) { die ('No action specified'); } echo $_POST['q']; 

And every time I run my Python App I get the 'No action specified' text printed to my console. I'm going to try to implement it using the Request Objects as I've seen a few demos that include those, but I'm wondering if anyone can help me explain why I don't get a Post Request with this code. Thanks!

-- EDITED --

This code does work and Posts to my web page properly:

data = urllib.urlencode({'q': 'Status'}) h = httplib.HTTPConnection('myserver:8080') headers = {"Content-type": "application/x-www-form-urlencoded",             "Accept": "text/plain"} h.request('POST', '/inout-tracker/index.php', data, headers) r = h.getresponse() print r.read() 

I am still unsure why the urllib2 library doesn't Post when I provide the data parameter - to me the docs indicate that it should.

like image 903
g.d.d.c Avatar asked Jul 13 '10 15:07

g.d.d.c


People also ask

What is the difference between Urllib and urllib2?

1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL. 2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.

Which is better Urllib or requests?

2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2. Requests – Requests' is a simple, easy-to-use HTTP library written in Python.


1 Answers

u = urllib2.urlopen('http://myserver/inout-tracker', data) h.request('POST', '/inout-tracker/index.php', data, headers) 

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

like image 90
bobince Avatar answered Oct 06 '22 07:10

bobince