Skip to content

Instantly share code, notes, and snippets.

@guillem
Created December 21, 2017 15:12
Show Gist options
  • Save guillem/8361913297b570e0540bba3ca302b53c to your computer and use it in GitHub Desktop.
Save guillem/8361913297b570e0540bba3ca302b53c to your computer and use it in GitHub Desktop.
Simple HTTP server that sleeps and returns random data as requested. Useful to mock other services simulating latency.
#!/usr/bin/env python
# HTTP Stochastic Sleeper
#
# Usage example: run this script with Python and visit the URL
#
# http://127.0.0.1:8080/httpss?sleep=500&size=1000
#
# This will sleep 500 milliseconds and then return 1000 bytes.
import http.server, random, re, string, time
class HttpssRequestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.protocol_version = 'HTTP/1.1'
match = re.search(r'^/httpss\?sleep=(?P<sleep>\d+)&size=(?P<size>\d+)$', self.path)
if match:
p_sleep = int(match.group('sleep')) / 1000.0
p_size = int(match.group('size'))
message = ''.join(random.choices(string.ascii_letters + string.digits + string.punctuation, k=p_size))
b_message = bytes(message, "utf8")
self.send_response(200)
self.send_header('Content-type','text/plain')
self.send_header('Content-length', len(b_message))
self.end_headers()
time.sleep(p_sleep)
self.wfile.write(b_message)
else:
message = '404 Not Found'
b_message = bytes(message, "utf8")
self.send_response(404)
self.send_header('Content-type', 'text/plain')
self.send_header('Content-length', len(b_message))
self.end_headers()
self.wfile.write(b_message)
if __name__ == '__main__':
httpss = http.server.HTTPServer(('127.0.0.1', 8080), HttpssRequestHandler)
httpss.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment