用python在服务器端处理HTTP GET输入参数

2024-06-28 19:58:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了一个简单的HTTP客户机和服务器来进行实验。下面的第一个代码片段显示了如何使用名为imsi的参数发送HTTP GET请求。在第二个代码片段中,我在服务器端展示了dou-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)

Tags: thepathselfsend客户端outputhtmlsys
3条回答

cgi模块包含FieldStorage类,该类应该在CGI上下文中使用,但似乎也很容易在上下文中使用。

BaseHTTPServer是一个相当低级的服务器。一般来说,你想使用一个真正的web框架来完成这类工作,但是既然你要求。。。

首先导入一个url解析库。在Python 2中,x是urlparse。(在Python3中,您将使用urllib.parse

import urlparse

然后,在dou-get方法中,解析查询字符串。

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

另外,您可以在客户机代码中使用urllib,这可能会简单得多。

可以使用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

相关问题 更多 >