Skip to content

Instantly share code, notes, and snippets.

@llekn
Last active January 7, 2024 23:35
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save llekn/67c7a6d77a6da0a56329 to your computer and use it in GitHub Desktop.
Save llekn/67c7a6d77a6da0a56329 to your computer and use it in GitHub Desktop.
HTTP server that print what is requested to console. Useful for debugging purposes.
#!/usr/bin/env python3
'''Usage:
python3 http-stdout-echo.py -a <bind-address> -p <bind-port>
Examples:
python3 http-stdout-echo.py # (will listen at 127.0.0.1:8080 by default)
python3 http-stdout-echo.py -a 10.3.1.3 -p 5555'''
from http.server import HTTPServer, BaseHTTPRequestHandler
class DummyHTTPHandler(BaseHTTPRequestHandler):
'''Simple HTTP server. Print to stdout every requests made to it.
Useful for development or debbuging... At least for me!'''
def __init__(self, request, client_address, server, read_from):
if read_from != None:
self.response = open(read_from).read()
else:
self.response = ''
return super().__init__(request, client_address, server)
def do_GET(self):
print('### GET {} - {} - {}'.format(self.client_address, self.request_version, self.path))
print('\n### Headers ###\n' + str(self.headers))
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(self.response.encode('utf-8'))
def do_POST(self):
msg_length = int(self.headers['Content-Length'])
print('### POST {} - {} - {}'.format(self.client_address, self.request_version, self.path))
print('\n### Headers ###\n' + str(self.headers))
print('\n### POST content ###\n{}'.format(self.rfile.read(msg_length)))
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(self.response.encode('utf-8'))
def do_OPTIONS(self):
print('### OPTIONS {} - {} - {}'.format(self.client_address, self.request_version, self.path))
print('\n### Headers ###\n' + str(self.headers))
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers')
self.end_headers()
self.wfile.write(self.response.encode('utf-8'))
if __name__ == '__main__':
import argparse
# Command line argument handling:
parser = argparse.ArgumentParser(description='Dummy HTTP server. Prints everything to stdout')
parser.add_argument('-a', '--address', help='default: 127.0.0.1')
parser.add_argument('-p', '--port', help='default: 8080', type=int)
parser.add_argument('-r', '--read_from', help='path to file to read and send as response', default=None, type=str)
args = parser.parse_args()
server = HTTPServer(
(args.address or '127.0.0.1', args.port or 8080),
lambda request, client_address, server: DummyHTTPHandler(request, client_address, server, args.read_from),
)
server.serve_forever()
@gamesbook
Copy link

I keep getting an error:

Exception happened during processing of request from ('127.0.0.1', 37422)
Traceback (most recent call last):
  File "/home/gamesbook/anaconda3/lib/python3.7/socketserver.py", line 316, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/home/gamesbook/anaconda3/lib/python3.7/socketserver.py", line 347, in process_request
    self.finish_request(request, client_address)
  File "/home/gamesbook/anaconda3/lib/python3.7/socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "http_stdout_echo.py", line 76, in <lambda>
    request, client_address, server, args.read_from),
  File "http_stdout_echo.py", line 18, in __init__
    self.response = open(read_from).read()
TypeError: expected str, bytes or os.PathLike object, not NoneType

@llekn
Copy link
Author

llekn commented Jul 3, 2020

Hi @gamesbook... better late than never...

The error is weird because the traceback line numbers doesn't match the lines of this gist. Maybe you modified the script?

@gkotian
Copy link

gkotian commented Nov 27, 2021

Thanks a lot for this. I found it super helpful for testing.

@llekn
Copy link
Author

llekn commented Nov 29, 2021

hey @gkotian cool to know that it is useful to somebody else besides me! 👍🏼 Feel free to comment if there is something to improve about this.

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