Thursday, April 28, 2005

Poor man's Web services with HTTP POST

I use HTTP POST as a lightweight mechanism for posting test results to a central location. I have tests running on various clients/platforms/OSes, and I need a way to keep track of the results of those tests. For this, I have an Apache server running CGI scripts that talk to a Firebird database. By using HTTP POST from the clients to the Apache server, I keep things simple, because the clients don't need to have any database bindings or drivers installed. In fact, all the clients need to know is how to open a socket on port 80 to the Web server.

This can be looked at as a poor man's Web service mechanism.

Here is the http_post function I'm using:

def http_post(data, cgi_cmd, webserver=""):
if not webserver:
webserver = "mywebserver.mydomain.com"
if type(data) == type(u''): # unicode
data = data.encode('iso-8859-1')

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((webserver, 80))
except:
print "Error: Could not connect to " + webserver
return

url = "http://%s/cgi-bin/%s" % (webserver, cgi_cmd)

sock.send("POST %s HTTP/1.0\n" % url)
sock.send("Accept: */*\n")
sock.send("User-Agent: http_post_mechanism\n")
sock.send("Content-Type: application/x-www-form-urlencoded\n")
sock.send("Content-Length: %d\n\n" % len(data))
sock.send(data)
while 1:
response = sock.recv(8192)
if not response: break
output = response
sock.close()

0 Comments:

Post a Comment

<< Home