Python Forum

Full Version: Handle parameters in POST request for python webserver?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a python webserver:

from http.server import HTTPServer, BaseHTTPRequestHandler

from io import BytesIO


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, world!')

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(b'This is a POST request \n')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())

httpd = HTTPServer(('localhost', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()
Made from various snippets of code I've pieced together from forums. I want a simple webserver that accepts GET and POST requests.

Let's say I have a POST request:
localhost:8080/?paramone=alpha&paramtwo=bravo&paramthree=charlie

And I want to return the value of 'paramtwo' two the user, how do I go about doing this?
Since the parameter paramtwo is shown in your url, this is definitely GET-request (or may be you have this parameter is sent as POST too behind the scene). To get get-parameters you need to parse self.path, e.g. something like this (not tested):

import urllib
print(urllib.parse.parse_qs(self.path))