[Web-SIG] how to post from a cgi script and not a html form??
alex at puddlejumper.foxybanana.com
Mon Nov 5 03:38:02 CET 2007
On Sun, Nov 04, 2007 at 05:14:31PM -0800, Jeff Peery wrote:
> I'm pretty new to using python on the web, I've got a bit of code
> that works pretty well to get form inputs and such. Now I need to post
> some info to a gateway service (for credit card processing) and then
> receive their response and do something with it. I can do this no
> problem... except that I'm not sure how to post my dictionary (name
> value pairs from form inputs i.e., credit card num, expire dates etc)
> from the cgi script. I had been using the html forms to submit data to
> the server, but now I need to do this from my cgi script. I think this is
> pretty straight forward but I didn't see anything in the cgi module.
> where do I start, or does anyone have some sample code? thanks!!
You'll need httplib which luckily come with the stdlib so no need to install
Something like this should get you going:
conn = httplib.HTTPConnection(remote_server)
values = '&'.join([ '%s=%s' % a for a in values.items() ])
conn.request(method, url, values, headers=headers)
res = conn.getresponse()
data = res.read()
return (res.status, res.reason, output)
the important bits here are our crappy makeshift
application/x-www-form-urlencoded rncoder which
is the values line and our setting of the content-type. We also
need to make sure the method passed to conn.request is 'POST' or
'PUT' (almost certainly POST) as these are the only ones that accept
a body. I think the cgi module may have a better way of doing the
encoding, but i've never found it.
More information about the Web-SIG