473,775 Members | 2,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

POST from a CGI

I'm receiving POST data to a CGI, which I'd like to forward to another
CGI using urllib2.

I have two options -

1) Parse the data using cgi.FieldStorag e() and then rebuild the POST
request into a dictionary - including any files (? uploading files by
urllib2 untested and undocumented - examples seem to be for httplib).

2) Read the whole POST data in using sys.stdin.read( ), rebuild the
'Content-type' and 'Content-length' headers and make the POST.

Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm
getting 400 errors when I try it (server thinks request is malformed).
I've checked the headers and the body data and they seem normal and I
can't work it out.

I wonder if anyone can see what I'm doing wrong......
(Simple code shown first - then a straightforward example that ought
to work and fails).

MAXUPLOAD = 10000 # set
max file size of 10 000 bytes
txdata = None
if os.environ.get( 'REQUEST_METHOD ','').lower()== 'post': # read
in the POST data from stdin
txdata = sys.stdin.read( MAXUPLOAD)
if len(txdata)==MA XUPLOAD and sys.stdin.read( 1):
print overmax
sys.exit(1) #
print an error message if too big a file is uploaded
envdict = { 'HTTP_CACHE_CON TROL' : 'Cache-control', 'CONTENT_TYPE' :
'Content-type',
'HTTP_ACCEPT_LA NGUAGE' : 'Accept-language', 'HTTP_ACCEPT'
: 'Accept',
'HTTP_PRAGMA' : 'Pragma', 'HTTP_CONNECTIO N' :
'Connection',
} #
these are request headers from the browser to the CGI
# that
we're going to rebuild from the environment variables
defaultuseragen t = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
# default User-agent
txheaders = {}
for envvar, header in envdict.items() : # go through
the environment variables putting any headers back
testval = os.environ.get( envvar)
if testval:
txheaders[header] = testval
txheaders['User-agent'] = os.environ.get( 'HTTP_USER_AGEN T',
defaultuseragen t) # put in a default user agent if we haven't got
one
if txdata and txheaders.has_k ey('Content-type'):
txheaders['Content-length'] = str(len(txdata) ) # we only need a
'Content-length' header if we have a 'Content-type' one...

theurl = 'http://www.someserver. com/somepath/somepage.html' #
In actual fact I normally decode the url from the PATH_INFO

req = urllib2.Request (theurl, txdata, txheaders) # create the
request object
try:
u = urllib2.urlopen (req) # fetch a handle on the url !
except IOError, e:
if not hasattr(e,'code '):
thecode = 0
else:
thecode = e.code
print 'Content-type: text/html'
print '<HTML><BODY><H 1>Error Code %s</H1></BODY></HTML>' % e.code

info = u.info() # info about the url
pagetype = info.gettype()
print 'Content-type: ' + pagetype + '\n'
print u.read() # print the received page

############### ############### ############### ############### ###

In the code I actually use I make a logfile as well which logs txdata,
txheaders and all the environment variables.

Making a simple post to my guestbook (
http://www.voidspace.xennos.com/cgi-bin/guestbook.py ) using this
method I get a 400 error.
From the log I can see the following headers :
(printed using headername, ' : ', value)

Connection : keep-alive
Accept-language : en-gb
Pragma : no-cache
Cache-control : max-age=259200
Content-type : application/x-www-form-urlencoded
Content-length : 62
Accept : image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
application/x-shockwave-flash, application/msword, */*
User-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
And the following POST data :
name=Fuzzyman&e mail=&homepage= &location=&comm ent=CGI+post+te st

Which even has a length of 62.... The only thing I can think of is
that the headers are appearing in the wrong order ?
Can anyone else see what I'm doing wrong ?

Regards,
Fuzzy
http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #1
5 3972
fu******@gmail. com (Michael Foord) writes:
I'm receiving POST data to a CGI, which I'd like to forward to another
CGI using urllib2.

I have two options -

1) Parse the data using cgi.FieldStorag e() and then rebuild the POST
request into a dictionary - including any files (? uploading files by
urllib2 untested and undocumented - examples seem to be for httplib).

2) Read the whole POST data in using sys.stdin.read( ), rebuild the
'Content-type' and 'Content-length' headers and make the POST.

Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm
getting 400 errors when I try it (server thinks request is malformed).
I've checked the headers and the body data and they seem normal and I
can't work it out.

I wonder if anyone can see what I'm doing wrong......
(Simple code shown first - then a straightforward example that ought
to work and fails). [snip] info = u.info() # info about the url
pagetype = info.gettype()
print 'Content-type: ' + pagetype + '\n'
print u.read() # print the received page


I think this is your problem: print is adding an extra \n to the end,
so the length of the data doesn't agree with the Content-length
header. Use sys.stdout.writ e.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)phy sics(dot)mcmast er(dot)ca
Jul 18 '05 #2
Sorry to top post... but it looks like my problem may be with the
latest version of ClientCookie rather than with the principles of what
I'm doing...

Fuzzy

fu******@gmail. com (Michael Foord) wrote in message news:<6f******* *************** ****@posting.go ogle.com>...
I'm receiving POST data to a CGI, which I'd like to forward to another
CGI using urllib2.

I have two options -

1) Parse the data using cgi.FieldStorag e() and then rebuild the POST
request into a dictionary - including any files (? uploading files by
urllib2 untested and undocumented - examples seem to be for httplib).

2) Read the whole POST data in using sys.stdin.read( ), rebuild the
'Content-type' and 'Content-length' headers and make the POST.

Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm
getting 400 errors when I try it (server thinks request is malformed).
I've checked the headers and the body data and they seem normal and I
can't work it out.

I wonder if anyone can see what I'm doing wrong......
(Simple code shown first - then a straightforward example that ought
to work and fails).

MAXUPLOAD = 10000 # set
max file size of 10 000 bytes
txdata = None
if os.environ.get( 'REQUEST_METHOD ','').lower()== 'post': # read
in the POST data from stdin
txdata = sys.stdin.read( MAXUPLOAD)
if len(txdata)==MA XUPLOAD and sys.stdin.read( 1):
print overmax
sys.exit(1) #
print an error message if too big a file is uploaded
envdict = { 'HTTP_CACHE_CON TROL' : 'Cache-control', 'CONTENT_TYPE' :
'Content-type',
'HTTP_ACCEPT_LA NGUAGE' : 'Accept-language', 'HTTP_ACCEPT'
: 'Accept',
'HTTP_PRAGMA' : 'Pragma', 'HTTP_CONNECTIO N' :
'Connection',
} #
these are request headers from the browser to the CGI
# that
we're going to rebuild from the environment variables
defaultuseragen t = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
# default User-agent
txheaders = {}
for envvar, header in envdict.items() : # go through
the environment variables putting any headers back
testval = os.environ.get( envvar)
if testval:
txheaders[header] = testval
txheaders['User-agent'] = os.environ.get( 'HTTP_USER_AGEN T',
defaultuseragen t) # put in a default user agent if we haven't got
one
if txdata and txheaders.has_k ey('Content-type'):
txheaders['Content-length'] = str(len(txdata) ) # we only need a
'Content-length' header if we have a 'Content-type' one...

theurl = 'http://www.someserver. com/somepath/somepage.html' #
In actual fact I normally decode the url from the PATH_INFO

req = urllib2.Request (theurl, txdata, txheaders) # create the
request object
try:
u = urllib2.urlopen (req) # fetch a handle on the url !
except IOError, e:
if not hasattr(e,'code '):
thecode = 0
else:
thecode = e.code
print 'Content-type: text/html'
print '<HTML><BODY><H 1>Error Code %s</H1></BODY></HTML>' % e.code

info = u.info() # info about the url
pagetype = info.gettype()
print 'Content-type: ' + pagetype + '\n'
print u.read() # print the received page

############### ############### ############### ############### ###

In the code I actually use I make a logfile as well which logs txdata,
txheaders and all the environment variables.

Making a simple post to my guestbook (
http://www.voidspace.xennos.com/cgi-bin/guestbook.py ) using this
method I get a 400 error.
From the log I can see the following headers :
(printed using headername, ' : ', value)

Connection : keep-alive
Accept-language : en-gb
Pragma : no-cache
Cache-control : max-age=259200
Content-type : application/x-www-form-urlencoded
Content-length : 62
Accept : image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
application/x-shockwave-flash, application/msword, */*
User-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
And the following POST data :
name=Fuzzyman&e mail=&homepage= &location=&comm ent=CGI+post+te st

Which even has a length of 62.... The only thing I can think of is
that the headers are appearing in the wrong order ?
Can anyone else see what I'm doing wrong ?

Regards,
Fuzzy
http://www.voidspace.org.uk/atlantib...thonutils.html

Jul 18 '05 #3
co**********@ph ysics.mcmaster. ca (David M. Cooke) wrote in message news:<qn******* ******@arbutus. physics.mcmaste r.ca>...
fu******@gmail. com (Michael Foord) writes:
I'm receiving POST data to a CGI, which I'd like to forward to another
CGI using urllib2.

I have two options -

1) Parse the data using cgi.FieldStorag e() and then rebuild the POST
request into a dictionary - including any files (? uploading files by
urllib2 untested and undocumented - examples seem to be for httplib).

2) Read the whole POST data in using sys.stdin.read( ), rebuild the
'Content-type' and 'Content-length' headers and make the POST.

Obviously (2) is a *lot* less fiddly and less error prone. *But* I'm
getting 400 errors when I try it (server thinks request is malformed).
I've checked the headers and the body data and they seem normal and I
can't work it out.

I wonder if anyone can see what I'm doing wrong......
(Simple code shown first - then a straightforward example that ought
to work and fails).

[snip]
info = u.info() # info about the url
pagetype = info.gettype()
print 'Content-type: ' + pagetype + '\n'
print u.read() # print the received page


I think this is your problem: print is adding an extra \n to the end,
so the length of the data doesn't agree with the Content-length
header. Use sys.stdout.writ e.


Those instructions occur *after* the 400 error. The 400 occurs when
the request is first sent to the server..... In actual fact I think
the problem is with the bleeding edge version of ClientCookie I was
using. When I tested my code with urllib2 it worked as expected !!

Thanks

Michael Foord
http://www.voidspace.org.uk/atlanitb...thonutils.html
Jul 18 '05 #4
[Michael Foord]
Sorry to top post...


Just don't. (be sorry, top post) :-)
Jul 18 '05 #5
Ha... thanks...

Fuzzy

P.S. want a gmail account ? I have a few invites left.....
On Thu, 23 Sep 2004 08:33:18 -0400, François Pinard
<pi****@iro.umo ntreal.ca> wrote:
[Michael Foord]
Sorry to top post...


Just don't. (be sorry, top post) :-)


--
http://www.Voidspace.org.uk
The Place where headspace meets cyberspace. Online resource site -
covering science, technology, computing, cyberpunk, psychology,
spirituality, fiction and more.

---
http://www.Voidspace.org.uk/atlantib...thonutils.html
Python utilities, modules and apps.
Including Nanagram, Dirwatcher and more.
---
http://www.fuchsiashockz.co.uk
http://groups.yahoo.com/group/void-shockz
---

Everyone has talent. What is rare is the courage to follow talent
to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy.
-Milan Kundera
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
3131
by: Thomas Scheiderich | last post by:
I am trying to understand Session variables and ran into a question on how they work with data that is passed. I have an HTM file that calls an ASP file and sends the name either by GET or POST. When I find is that if I send the value by the GET method, response.write("From QueryString: " & Request.QueryString("usernamefromform") & "<br><br>")
1
4783
by: khawar | last post by:
my application is in asp.net using C# hi guys having a complicated problem i am using payflowlink to process CC payments I have to send a httppost to their servers. The problem is how do i do a post where i get these values like the amount from the database. eg of the post: <form method="post" action="https://payflowlink.verisign.com/payflowlink.cfm"> <input type="hidden" name="name" value="john adams">
2
12562
by: Matt | last post by:
When we submit the form data to another page, we usually do the following: <form action="display.aspx" method="post"> will submit the form data and open display.asp in the current browser <form action="display.aspx" method="post" target="_blank"> will submit the form data and open display.asp in a new browser
1
2976
by: Manuel | last post by:
I have to log into a website and retrieve some information. The problem is that the post isn't "normal". I'm used to passing post values in the form of: Variable1=Value1&Variable2=Value2 etc. I used Live Http Headers to retrieve the POST information, I included it at the end of this message. Can anyone tell me how to make THIS kind of post? Another thing, "Content-Type: multipart/form-data;
10
3440
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a database or continue to process on to the next page. I am now trying to learn ASP to see if we can replace some of our applications that were written in php with an ASP alternative. However, after doing many searches on google and reading a couple...
24
2884
by: moriman | last post by:
Hi, The script below *used* to work. I have only just set up a server, PHP etc again on my Win98 system and now it doesn't? On first loading this page, you would have $p = and the button image below it.
9
3100
by: c676228 | last post by:
Hi, I am new to this discussion forum. I started to post questions on this forum since this Jan. and got many good responses and I am very appreciated to those who are willing to help with their expertise. That save me a lot of time and stress. I want to rate the post, but I only see questions "is this post helpful" and " why should I rate a post" link. I didn't see any thing "rate the post" link. I already sign into the community...
3
4930
by: JansenH | last post by:
We have implemented a 'HTTP Post' client in C# that posts Xml documents to a webserver. This is working fine if the post rate is one post for every 20 seconds. But if the post rate is increased to one post for every 10 seconds the client start getting error 403 'forbidden' from the webserver after a short period of time. The webserver is IIS. The choking of the client/server communication when doing high frequency posting is due to that we...
10
15727
by: Peter Michaux | last post by:
Hi, All Ajax libraries I've read use encodeURIComponent() on the name- value pairs extracted from forms before POST ing the result to the server with and xmlhttprequest. I can understand why this encoding is required in the case of a GET request and the form data is attached as a URI query string; however, why is the encoding necessary for POST requests? Thanks,
0
9622
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10268
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10107
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10048
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8939
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6718
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4017
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2853
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.