6

I'm trying to set up a HTTP server in a Python script. So far I got the server it self to work, with a code similar to the 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 variables from the GET request, so if server.py?var1=hi is requested, I need the Python code to put var1 into a Python variable and process it (like print it). How would I go about this? Might be a simple question to you Python pros, but this Python beginner doesn't know what to do! Thanks in advance!

2 Answers 2

9

Import urlparse and do:

def do_GET(self):
    qs = {}
    path = self.path
    if '?' in path:
        path, tmp = path.split('?', 1)
        qs = urlparse.parse_qs(tmp)
    print path, qs
Sign up to request clarification or add additional context in comments.

1 Comment

One can also apply parse_qs to urlparse(self.path).query instead of splitting path manually.
6

urlparse.parse_qs()

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

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

Import in Python 3: from urllib.parse import urlparse

3 Comments

I did come across that, but I'm not sure how to integrate this... Could you give me a short example?
urlparse.parse_qs() returns a dictionary. Use it as you would any other dictionary in Python.
Just checked this answer, and I can't find where BaseHTTPServer sets environment variables. CGIHTTPServer does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.