2012-01-19 4 views
13

Ho scritto un semplice client e server HTTP in python per l'esperimento. Il primo frammento di codice qui sotto mostra come invio una richiesta get HTTP con un parametro vale a dire imsi. Nel secondo frammento di codice mostro la mia implementazione della funzione doGet sul lato server. La mia domanda è come posso estrarre il parametro imsi nel codice del server e inviare una risposta al client per segnalare al client che imsi è valido. Grazie.Elaborazione HTTP Parametro di input GET sul lato server in python

P.S .: ho verificato che il client invia la richiesta con successo.

codice client frammento di

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() 

codice server frammento di

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

non si ottiene il 'args' inviato con la richiesta' GET'? – aayoubi

+0

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

risposta

23

È possibile analizzare la query di una richiesta GET utilizzando urlparse, quindi dividere la stringa di query.

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"] } 

È possibile confermare questo utilizzando

curl http://your.host/?imsi=Hello 
+1

& è un carattere speciale di shell ... Ha bisogno di essere scappato così il tuo comando di arricciatura passa sia params –

+0

Ah, naturalmente, grazie per lo spotting che =) –

+1

Con Python 3, usare 'da urllib.parse import urlparse' source: https://stackoverflow.com/a/5239594/4669135 –

9

BaseHTTPServer è un server piuttosto di basso livello. Generalmente vuoi utilizzare un vero framework web che funzioni per te, ma da quando hai chiesto ...

Prima di tutto importare una libreria di analisi url. In Python 2, x è urlparse. (In python3, utilizza urllib.parse)

import urlparse 

Poi, nel metodo do_GET, analizzare la stringa di query.

imsi = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('imsi', None) 
print imsi # Prints None or the string value of imsi 

Inoltre, si potrebbero utilizzare urllib nel codice cliente e probabilmente sarebbe molto più facile.

0

cgi Il modulo contiene la classe FieldStorage che dovrebbe essere utilizzata nel contesto CGI, ma sembra essere facilmente utilizzata anche nel proprio contesto.