F. *_*mir 20 python webserver get http
我用Python编写了一个简单的HTTP客户端和服务器进行实验.下面的第一个代码片段显示了我如何使用名为imsi的参数发送HTTP GET请求.在第二个代码片段中,我在服务器端显示了我的do_Get函数实现.我的问题是如何在服务器代码中提取imsi参数并将响应发送回客户端,以便向客户端发出imsi有效的信号.
谢谢.
PS:我验证了客户端成功发送请求.
CLIENT代码段
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()
Run Code Online (Sandbox Code Playgroud)
SERVER代码段
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)
Run Code Online (Sandbox Code Playgroud)
ib.*_*ren 45
您可以使用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"] }
Run Code Online (Sandbox Code Playgroud)
您可以使用确认
curl http://your.host/?imsi=Hello
Run Code Online (Sandbox Code Playgroud)
Ken*_*der 16
BaseHTTPServer是一个非常低级别的服务器.一般来说,你想使用一个真正的网络框架为你做这种笨拙的工作,但既然你问...
首先导入一个url解析库.在Python 2中,x是urlparse.(在Python3中,你使用urllib.parse)
import urlparse
Run Code Online (Sandbox Code Playgroud)
然后,在do_get方法中,解析查询字符串.
imsi = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('imsi', None)
print imsi # Prints None or the string value of imsi
Run Code Online (Sandbox Code Playgroud)
此外,您可能在您的客户端代码中使用urllib,它可能会更容易.
归档时间: |
|
查看次数: |
52100 次 |
最近记录: |