Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Friday, November 30, 2012

Simple HTTP POST Server / Client with Python

Continue from the last post, it's about simple HTTP server with Python. Today, I will explain more about create POST server with Python. From last time to response GET request, we need to override do_GET in class SimpleHTTPRequestHandler. Similarly, to response POST request, we just override do_POST method. However, to receive parameters from POST there are 2 popular formats: url-encode, and multipart as I described in my previous post

In this post I will describe only url-encode. It's like encrypt the data in url format before sending to the server. So, your data will be like "{key1}={value1}&{key2}={value2} ...:". Basically, it's not that difficult with Python because all we need, are already had.

HTTP POST Client:
import urllib, urllib2

uri = 'http://localhost:8000'
name = "Mark"
# Encode data in base64 string
encode = name.encode('base64')
params = { 'name' : encode }
# Pack key-value pairs in form of url-encode format
data = urllib.urlencode(params)

# urlopen with data will use POST method by default
p = urllib2.urlopen(uri, data)
print p.read()
HTTP POST Server:
import SimpleHTTPServer
import SocketServer
import cgi
from base64 import decodestring

# Server port
PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  
        def do_POST(self):
                # Use cgi module to retrieve data from POST as a form
                form = cgi.FieldStorage(
                        fp=self.rfile,
                        headers=self.headers,
                        environ={'REQUEST_METHOD':'POST',
                                 'CONTENT_TYPE':self.headers['Content-Type'],
                                 })
                # We can get value from the form key like we did in dictionary class
                encode = form['name'].value
                # Decide the value from base64 string
                decode = decodestring(encode)
                self.wfile.write('Hello, ' + decode + '.')
                
Handler = ServerHandler

# Initialize server object
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

1 comment:

  1. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us.
    Learn AWS certification in high-grade training in Cognex Technologies. Cognex providing good quality in services and development in the field of project management and IT Management.
    AWS Training in Chennai

    ReplyDelete