New User - Using tutorial and Docs - POST returns 302 Found

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 2 21:05:08 EST 2009


En Mon, 02 Mar 2009 23:02:10 -0200, JohnV <loftmaster at gmail.com> escribió:

> I have to run the program one time just to get the dynamically
> generated redirect URL for the POST (it looks like this)
> The document has moved <a href="http://www.thenational.us/pages/htmlos/
> 001863.1.059070780420726458">
>
> I then paste the redirected URL ("http://www.thenational.us/pages/
> htmlos/001863.1.059070780420726458) into the script and run it again
> and it works.

Let urllib2 handle the redirect for you.

> f = open('C:\Users\Owner\Desktop\mydata.txt', 'r')
> read_data = f.read()
>
> f.close()
>
> import httplib, urllib
> params = urllib.urlencode({'textarea1': read_data})
> headers = {"Content-type": "application/x-www-form-urlencoded",
> "Accept": "text/plain"}
> conn = httplib.HTTPConnection("thenational.us:80")
> conn.request("POST", "/pages/htmlos/001863.5.083914970120726458",
> params, headers)
> response = conn.getresponse()

Replace the above three lines with:

url = "http://thenational.us:80/pages/htmlos/001863.5.083914970120726458"
req = urllib2.Request(url, params, headers)
response = urllib2.urlopen(req)

> print response.status, response.reason
> data = response.read()
> conn.close()
>
> f = open('C:\Users\Owner\Desktop\pydata.txt', 'a')
> f.write(data)
> f.close()
> --

For more info on using urllib2, see  
http://www.voidspace.org.uk/python/articles/urllib2.shtml

-- 
Gabriel Genellina




More information about the Python-list mailing list