Skip to content

Instantly share code, notes, and snippets.

@I159
Last active November 22, 2019 12:53
Show Gist options
  • Save I159/a1bc91bdf046442de1e12d25d59e65ad to your computer and use it in GitHub Desktop.
Save I159/a1bc91bdf046442de1e12d25d59e65ad to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# Reflects the requests from HTTP methods GET, POST, PUT, and DELETE
# Written by Nathan Hamiel (2010)
# Adapted to Python 3 by Ilya "I159" Pekenly (2019)
import json
import pprint
from http import server
from optparse import OptionParser
class RequestHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
print("\n----- Request Start ----->\n")
print(self.path)
print(self.headers)
print("<----- Request End -----\n")
self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
def do_POST(self):
print("\n----- Request Start ----->\n")
print(self.path)
content_length = self.headers.get("content-length")
length = int(content_length) if content_length else 0
print(self.headers)
pprint.pprint(json.loads(self.rfile.read(length)))
print("<----- Request End -----\n")
self.send_response(200)
do_PUT = do_POST
do_DELETE = do_GET
def main():
port = 3000
print("Listening on localhost:%s" % port)
local_server = server.HTTPServer(("", port), RequestHandler)
local_server.serve_forever()
if __name__ == "__main__":
parser = OptionParser()
parser.usage = (
"Creates an http-server that will echo out any GET or POST parameters\n"
"Run:\n\n"
" reflect"
)
(options, args) = parser.parse_args()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment