Doing POST opperations from Python

Skip Montanaro skip at
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("",

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

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

Skip Montanaro |
skip at |
847-971-7098   | Python: Programming the way Guido indented...

More information about the Python-list mailing list