我把以下脚本放在一起,我希望在我的浏览器中返回“Hello World!('192.168.0.162',48344)bob”
server:8081/?first_name=bob
然而,当我运行以下程序时,它返回Hello World!('192.168.0.162',48344)无
#!/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()
有什么问题?
答案 0 :(得分:1)
问题是使用cgi.FieldStorage()
,它旨在用于CGI脚本。您必须自己在do_GET()
方法中解析查询字符串。您可以使用cgi
模块的某些部分来执行此操作(可能是do_POST()
处理程序中的最佳方法),但对于do_GET()
,更典型的方法是这样的:
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)