2012-01-19 57 views
13

我在python中編寫了一個簡單的HTTP客戶端和服務器用於體驗。下面的第一個代碼片段展示瞭如何使用一個參數(即imsi)發送HTTP請求。在第二個代碼片段中,我在服務器端顯示了我的doGet函數實現。我的問題是我如何在服務器代碼中提取imsi參數,並將響應發送回客戶端以便向客戶端發信號通知imsi有效。謝謝。在python中處理服務器端的HTTP GET輸入參數

P.S .:我確認客戶端成功發送請求。

客戶端代碼片斷

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 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) 
+0

難道你沒有得到與'GET'請求一起發送的'args'嗎? – aayoubi

+0

相關:https://stackoverflow.com/questions/2490162/parse-http-get-and-post-parameters-from-basehttphandler –

回答

23

您可以分析使用一個裏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 
+1

&是一個shell特殊字符...需要逃脫,所以你的捲曲命令通過params –

+0

當然,感謝您發現=) –

+1

在Python 3中,使用'from urllib.parse import urlparse' source:https://stackoverflow.com/a/5239594/4669135 –

9

BaseHTTPServer是一個非常低級別的服務器證實了這一點。通常你想使用一個真正的web框架,爲你做這種咕work工作,但因爲你問...

首先導入一個url解析庫。在Python 2中,x是urlparse。 (在Python3,你會使用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,它可能會方便很多。

0

cgi模塊包含FieldStorage類應該用於CGI上下文中,但似乎也很容易在您的上下文中使用。