在Python中获取HTTP GET变量

时间:2011-03-08 23:16:26

标签: python http get

我正在尝试在Python脚本中设置HTTP服务器。到目前为止,我从here获得了自己的服务器,代码类似于下面的代码。

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print("Just received a GET request")
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        self.wfile.write('Hello world')

        return

    def log_request(self, code=None, size=None):
        print('Request')

    def log_message(self, format, *args):
        print('Message')

if __name__ == "__main__":
    try:
        server = HTTPServer(('localhost', 80), MyHandler)
        print('Started http server')
        server.serve_forever()
    except KeyboardInterrupt:
        print('^C received, shutting down server')
        server.socket.close()

但是,我需要从GET请求获取变量,因此如果请求server.py?var1=hi,我需要Python代码将var1放入Python变量并处理它(如打印它)。我该怎么做?对Python专业人员来说可能是一个简单的问题,但是这个Python初学者不知道该怎么做!提前谢谢!

2 个答案:

答案 0 :(得分:6)

导入urlparse并执行:

def do_GET(self):
    qs = {}
    path = self.path
    if '?' in path:
        path, tmp = path.split('?', 1)
        qs = urlparse.parse_qs(tmp)
    print path, qs

答案 1 :(得分:5)

urlparse.parse_qs()

print urlparse.parse_qs(os.environ['QUERY_STRING'])

如果您关心订单或重复,urlparse.parse_qsl()

Import in Python 3: from urllib.parse import urlparse