Doing POST opperations from Python

Skip Montanaro skip at mojam.com
Tue Aug 31 14:30:43 EDT 1999


    Phil> I am trying to produce POST requests within python (to drive a web
    Phil> based email client). I can do GET requests, but can understand how
    Phil> to do post. I have read RFC1945 (Informational), but I can find
    Phil> the info there either.  I understand that the data is sent as part
    Phil> of the headers, but how?

Depends which module you're using.  If you use a recent version of urllib,
you can place your parameters in a dictionary, call urllib.urlencode to
encode it and pass the results to urllib.urlopen:

    import urllib
    paramstring = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query",
		       paramstring)
    print f.read()

If you're using httplib, you do basically the same thing at a slightly lower 
level:

    import httplib, urllib
    paramstring = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    h = httplib.HTTP("www.musi-cal.com:80")
    h.putrequest("POST", "/cgi-bin/query")
    h.putheader("Content-length", "%d"%len(paramstring))
    h.endheaders()
    h.send(paramstring)
    reply, msg, hdrs = h.getreply()
    print h.getfile().read()

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/~skip/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list