Shariq
Shariq

Reputation: 579

Python - POSTing with a urllib2 opener

I have a urllib2 opener, and wish to use it for a POST request with some data.

I am looking to receive the content of the page that I am POSTing to, and also the URL of the page that is returned (I think this is just a 30x code; so something along those lines would be awesome!).

Think of this as the code:

anOpener = urllib2.build_opener(???,???)
anOpener.addheaders = [(???,???),(???,???),...,(???,???)]
# do some other stuff with the opener 
data = urllib.urlencode(dictionaryWithPostValues)
pageContent = anOpener.THE_ANSWER_TO_THIS_QUESTION
pageURL = anOpener.THE_SECOND_PART_OF_THIS_QUESTION

Upvotes: 9

Views: 12432

Answers (3)

Thomas Spycher
Thomas Spycher

Reputation: 976

If you add data to the request the method gets automatically changed to POST. Check out the following example:

import urllib2
import json

url = "http://server.local/x/y"
data = {"name":"JackBauer"}
method = "PUT"
request = urllib2.Request(url)
request.add_header("Content-Type", "application/json")
request.get_method = lambda: method
if data: request.add_data(json.dumps(data))
response = urllib2.urlopen(request)
if response: print response.read()

As i mentioned the lambda is not needed if you use GET/POST.

Upvotes: 0

Shariq
Shariq

Reputation: 579

This is such a silly question once one realizes the answer.

Just use:

open(URL,data)

for the first part, and like Rachel Sanders mentioned,

geturl()

for the second part.

I really can't figure out how the whole Request/opener thing works though; I couldn't find any nice documentation :/

Upvotes: 6

Rachel Sanders
Rachel Sanders

Reputation: 5874

This page should help you out:

http://www.voidspace.org.uk/python/articles/urllib2.shtml#data

import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
      'location' : 'Northampton',
      'language' : 'Python' }

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
the_url  = response.geturl() # <- doc claims this gets the redirected url

It looks like you can also use response.info() to get the Location header directly instead of using .geturl().

Hope that helps!

Upvotes: 5

Related Questions