Skip to content

Instantly share code, notes, and snippets.

@automaticgiant
Last active October 20, 2018 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save automaticgiant/6eaf2daaf50efbe1c1bbfc7a08a80f55 to your computer and use it in GitHub Desktop.
Save automaticgiant/6eaf2daaf50efbe1c1bbfc7a08a80f55 to your computer and use it in GitHub Desktop.
python3 http.server extended
#!/usr/bin/env python3
'''
extension of [`http.server`](https://docs.python.org/3/library/http.server.html)
'''
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
class Handler(SimpleHTTPRequestHandler):
def do_POST(self):
'''handle HTTP POST by graciously accepting an upload (maybe bugged)'''
content_length = int(self.headers['Content-Length'])
self.log_message(f'got a request for {self.path}')
path = self.path[1:]
self.send_response(200)
self.end_headers()
msg = f"thanks - writing {content_length} bytes to {path}\n"
self.log_message(msg)
self.wfile.write(msg.encode('utf-8'))
body = self.rfile.read(content_length)
with open(path,'wb') as file:
file.write(body)
def do_PUT(self):
'''use a HTTP PUT request as a shutdown signal'''
msg = "got PUT; shutting down\n"
self.log_message(msg)
self.send_response(200)
self.end_headers()
self.wfile.write(msg.encode('utf-8'))
self.finish()
self.connection.close()
t = threading.Thread(target = self.server.shutdown)
t.start()
if __name__ == '__main__':
import os
nomad_env = lambda x: x.startswith('NOMAD')
if any(map(nomad_env, os.environ)):
print('nomad env looks like following: ')
print([f'{k},{v}' for k,v in os.environ.items() if nomad_env(k)])
http_addr = (os.getenv('NOMAD_IP_http','localhost'), int(os.getenv('NOMAD_PORT_http', 8000)))
print(f'ready to try to `serve_forever` {os.getcwd()} at {http_addr}')
HTTPServer(http_addr, Handler).serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment