webserver.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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(
  33. ('', args.port),
  34. SimpleHTTPRequestHandlerWithPOST
  35. )
  36. def run():
  37. os.chdir(dr)
  38. httpd.serve_forever()
  39. daemon = Daemonize(
  40. app="synapse-webclient",
  41. pid=args.pid,
  42. action=run,
  43. auto_close_fds=False,
  44. )
  45. daemon.start()
  46. if __name__ == '__main__':
  47. setup()