Extracting HTTP GET variables in Python

I am trying to configure an HTTP server in a Python script. So far I have the server itself worked with a code like below, from 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()

However, I need to get the variables from the GET request, so if requested server.py?var1=hi, I need the Python code to put var1into the Python variable and process it (e.g. print). How can i do this? Maybe a simple question for you is a Python pro, but this beginner Python doesn't know what to do! Thanks in advance!

+5
source share
2 answers

urlparse.parse_qs()

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

Or, if you care about the order or duplicates . urlparse.parse_qsl()

Import to Python 3: from urllib.parse import urlparse

+4

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
+6

All Articles