webserver.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import argparse
  2. import BaseHTTPServer
  3. import os
  4. import SimpleHTTPServer
  5. import cgi, logging
  6. from daemonize import Daemonize
  7. class SimpleHTTPRequestHandlerWithPOST(SimpleHTTPServer.SimpleHTTPRequestHandler):
  8. UPLOAD_PATH = "upload"
  9. """
  10. Accept all post request as file upload
  11. """
  12. def do_POST(self):
  13. path = os.path.join(self.UPLOAD_PATH, os.path.basename(self.path))
  14. length = self.headers["content-length"]
  15. data = self.rfile.read(int(length))
  16. with open(path, "wb") as fh:
  17. fh.write(data)
  18. self.send_response(200)
  19. self.send_header("Content-Type", "application/json")
  20. self.end_headers()
  21. # Return the absolute path of the uploaded file
  22. self.wfile.write('{"url":"/%s"}' % path)
  23. def setup():
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument("directory")
  26. parser.add_argument("-p", "--port", dest="port", type=int, default=8080)
  27. parser.add_argument("-P", "--pid-file", dest="pid", default="web.pid")
  28. args = parser.parse_args()
  29. # Get absolute path to directory to serve, as daemonize changes to '/'
  30. os.chdir(args.directory)
  31. dr = os.getcwd()
  32. httpd = BaseHTTPServer.HTTPServer(("", args.port), SimpleHTTPRequestHandlerWithPOST)
  33. def run():
  34. os.chdir(dr)
  35. httpd.serve_forever()
  36. daemon = Daemonize(
  37. app="synapse-webclient", pid=args.pid, action=run, auto_close_fds=False
  38. )
  39. daemon.start()
  40. if __name__ == "__main__":
  41. setup()