在Python中处理服务器端的HTTP GET输入参数
我用Python写了一个简单的HTTP客户端和服务器,主要是为了实验。下面的第一段代码展示了我如何发送一个带有imsi参数的HTTP GET请求。在第二段代码中,我展示了服务器端的do_Get函数的实现。我的问题是,如何在服务器代码中提取imsi参数,并向客户端发送响应,以便告诉客户端imsi是有效的。
谢谢。
附注:我确认客户端成功发送了请求。
客户端代码片段
params = urllib.urlencode({'imsi': str(imsi)})
conn = httplib.HTTPConnection(host + ':' + str(port))
#conn.set_debuglevel(1)
conn.request("GET", "/index.htm", 'imsi=' + str(imsi))
r = conn.getresponse()
服务器代码片段
import sys, string, cStringIO, cgi, time, datetime
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
# I want to extract the imsi parameter here and send a success response to
# back to the client.
def do_GET(self):
try:
if self.path.endswith(".html"):
#self.path has /index.htm
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("<h1>Device Static Content</h1>")
self.wfile.write(f.read())
f.close()
return
if self.path.endswith(".esp"): #our dynamic content
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("<h1>Dynamic Dynamic Content</h1>")
self.wfile.write("Today is the " + str(time.localtime()[7]))
self.wfile.write(" day in the year " + str(time.localtime()[0]))
return
# The root
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
lst = list(sys.argv[1])
n = lst[len(lst) - 1]
now = datetime.datetime.now()
output = cStringIO.StringIO()
output.write("<html><head>")
output.write("<style type=\"text/css\">")
output.write("h1 {color:blue;}")
output.write("h2 {color:red;}")
output.write("</style>")
output.write("<h1>Device #" + n + " Root Content</h1>")
output.write("<h2>Device Addr: " + sys.argv[1] + ":" + sys.argv[2] + "</h1>")
output.write("<h2>Device Time: " + now.strftime("%Y-%m-%d %H:%M:%S") + "</h2>")
output.write("</body>")
output.write("</html>")
self.wfile.write(output.getvalue())
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
4 个回答
1
如果你不想在大多数情况下引入额外的库,可以使用:
i = self.path.index ( "?" ) + 1
params = dict ( [ tuple ( p.split("=") ) for p in self.path[i:].split ( "&" ) ] )
21
BaseHTTPServer 是一个比较基础的服务器。一般来说,你会想用一个真正的网络框架来处理这些繁琐的工作,不过既然你问了……
首先,你需要导入一个用来解析网址的库。在 Python 2.x 中是 urlparse。(在 Python 3 中,你会用 urllib.parse)
import urlparse
然后,在你的 do_get 方法里,解析一下查询字符串。
imsi = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('imsi', None)
print imsi # Prints None or the string value of imsi
另外,你也可以在你的客户端代码中使用 urllib,这样可能会简单很多。
61
你可以使用urlparse来解析GET请求中的查询内容,然后把查询字符串分开。
from urlparse import urlparse
query = urlparse(self.path).query
query_components = dict(qc.split("=") for qc in query.split("&"))
imsi = query_components["imsi"]
# query_components = { "imsi" : "Hello" }
# Or use the parse_qs method
from urlparse import urlparse, parse_qs
query_components = parse_qs(urlparse(self.path).query)
imsi = query_components["imsi"]
# query_components = { "imsi" : ["Hello"] }
你可以通过使用
curl http://your.host/?imsi=Hello