Skip to content

Instantly share code, notes, and snippets.

@trungly
Last active February 1, 2024 18:51
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save trungly/5889154 to your computer and use it in GitHub Desktop.
Save trungly/5889154 to your computer and use it in GitHub Desktop.
A simple Python HTTP server that supports a GET that echoes some request data and a POST that reads a request body, parses it as JSON and responds with part of the data
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse, json
class GetHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse.urlparse(self.path)
message = '\n'.join([
'CLIENT VALUES:',
'client_address=%s (%s)' % (self.client_address,
self.address_string()),
'command=%s' % self.command,
'path=%s' % self.path,
'real path=%s' % parsed_path.path,
'query=%s' % parsed_path.query,
'request_version=%s' % self.request_version,
'',
'SERVER VALUES:',
'server_version=%s' % self.server_version,
'sys_version=%s' % self.sys_version,
'protocol_version=%s' % self.protocol_version,
'',
])
self.send_response(200)
self.end_headers()
self.wfile.write(message)
return
def do_POST(self):
content_len = int(self.headers.getheader('content-length'))
post_body = self.rfile.read(content_len)
self.send_response(200)
self.end_headers()
data = json.loads(post_body)
self.wfile.write(data['foo'])
return
if __name__ == '__main__':
from BaseHTTPServer import HTTPServer
server = HTTPServer(('localhost', 8080), GetHandler)
print 'Starting server at http://localhost:8080'
server.serve_forever()
@trungly
Copy link
Author

trungly commented Jun 29, 2013

based on http://doughellmann.com/2007/12/pymotw-basehttpserver.html

To test the POST with curl:
curl -d '{"foo":1}' localhost:8080

@GoulartNogueira
Copy link

Hi, I followed your tutorial, thanks.
But it can't handle special characters well...
I tried:

parsed_path = urlparse.urlparse(self.path)
query = parsed_path.query

But later, I fixed to:

parsed_path = urllib.parse.urlsplit(self.path)
query = urllib.parse.parse_qs(parsed_path.query)

And now it won't break. :)

@pkess
Copy link

pkess commented May 17, 2023

Hello @trungly,

i found your code and tested it with Python 3.10. Due to the changes in python in between i had to fix some imports, etc.
This is the result:

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
import json

class GetHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        parsed_path = urlparse(self.path)
        message = '\n'.join([
            'CLIENT VALUES:',
            'client_address=%s (%s)' % (self.client_address,
                self.address_string()),
            'command=%s' % self.command,
            'path=%s' % self.path,
            'real path=%s' % parsed_path.path,
            'query=%s' % parsed_path.query,
            'request_version=%s' % self.request_version,
            '',
            'SERVER VALUES:',
            'server_version=%s' % self.server_version,
            'sys_version=%s' % self.sys_version,
            'protocol_version=%s' % self.protocol_version,
            '',
            ])
        self.send_response(200)
        self.end_headers()
        self.wfile.write(message.encode('utf-8'))
        return

    def do_POST(self):
        content_len = int(self.headers.getheader('content-length'))
        post_body = self.rfile.read(content_len)
        self.send_response(200)
        self.end_headers()

        data = json.loads(post_body)

        self.wfile.write(data['foo'])
        return

if __name__ == '__main__':
    server = HTTPServer(('localhost', 8080), GetHandler)
    print('Starting server at http://localhost:8080')
    server.serve_forever()

I now tried to curl this with http://localhost:8085/Hallo.txt?Arg1=4&arg4=3 . But the code does not get the second argument called arg4 here. Does anyone know why?

@vli02
Copy link

vli02 commented Jun 1, 2023

try this: curl http://localhost:8080/"Hallo.txt?Arg1=4&arg4=3"

@pkess
Copy link

pkess commented Jun 13, 2023

try this: curl http://localhost:8080/"Hallo.txt?Arg1=4&arg4=3"

Thank you very much. To bad from my side. It helped a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment