I put together the following script that i would like to return the "Hello World !('192.168.0.162', 48344)bob" when in my browser i have
server:8081/?first_name=bob
however when i run the following program it returns Hello World !('192.168.0.162', 48344)None
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import cgi, cgitb
x = "1"
PORT_NUMBER = 8081
cgitb.enable()
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
form = cgi.FieldStorage()
first_name = form.getvalue('first_name')
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World !")
self.wfile.write(self.client_address)
self.wfile.write(first_name)
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
What is wrong?
The issue is using cgi.FieldStorage()
which is intended to be used in a CGI script. You have to parse the query string yourself in your do_GET()
method. You could use certain parts of the cgi
module to do that (and probably the best approach in a do_POST()
handler), but for do_GET()
the more typical approach is something like this:
import urlparse
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
o = urlparse.urlparse(self.path)
form = urlparse.parse_qs(o.query)
See urlparse.urlparse.
See urlparse.parse_qs.