在python中处理服务器端的HTTP GET输入参数 [英] Processing HTTP GET input parameter on server side in python
问题描述
我用python写了一个简单的HTTP客户端和服务器来体验。下面的第一个代码片段展示了如何使用一个参数(即imsi)发送HTTP请求。在第二个代码片段中,我在服务器端显示了我的doGet函数实现。我的问题是我如何在服务器代码中提取imsi参数,并将响应发送回客户端以便向客户端发信号通知imsi有效。谢谢。
PS:我确认客户端已成功发送请求。
客户端代码片段
$ b
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()
SERVER代码段
import sys,string,cStringIO,cgi,time,datetime $ b $ from os import curdir,sep
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class MyHandler(BaseHTTPRequestHandler):
我想要在这里提取imsi参数并发送成功响应给
#回到客户端。
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>设备静态内容< / h1>)
self.wfile.write(f.read())
f.close()
返回
if self.path.endswith(。esp):#our动态内容
self.send_response(200)
self.send_header('Content-type',' text / html')
self.end_headers()
self.wfile.write(< h1>动态动态内容< / h1>)
self.wfile.write(Today是+ str(time.localtime()[7]))
self.wfile.write(今年的日子+ str(time.localtime()[0]))
return
#根
self.send_response(200)
self.send_header('Content-type','text / html')
self.end_headers()
lst = list(sys.argv [1])$ b $ bn = 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>设备时间:+ now.strftime(%Y-%m - %d%H:%M:%S)+< / h2>)
output.write(< / body>)
output.write(< html>)
self.wfile.write(output.getvalue ())
返回
除了IOError:
self.send_error(404,'未找到文件:%s'%self.path)
您可以使用urlparse解析GET请求的查询,查询字符串。
from urlparse导入urlparse
查询= urlparse(self.path).query
query_components = dict(qc.split(=)for query.split(&))
imsi = query_components [imsi]
#query_components = {imsi:Hello }
#或者使用urlparse中的parse_qs方法
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
I wrote a simple HTTP client and server in python for experienmenting. The first code snippet below shows how I send an HTTP get request with a parameter namely imsi. In the second code snippet I show my doGet function implementation in the server side. My question is how I can extract the imsi parameter in the server code and send a response back to the client in order to signal the client that imsi is valid. Thanks.
P.S.: I verified that client sends the request successfully.
CLIENT code snippet
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()
SERVER code snippet
import sys, string,cStringIO, cgi,time,datetime
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
# I WANT TO EXTRACT 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)
You can parse the query of a GET request using urlparse, then split the query string.
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"] }
You can confirm this by using
curl http://your.host/?imsi=Hello
这篇关于在python中处理服务器端的HTTP GET输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!