Skip to content
Snippets Groups Projects
webserver.py 1.47 KiB
Newer Older
  • Learn to ignore specific revisions
  • matrix.org's avatar
    matrix.org committed
    import argparse
    import BaseHTTPServer
    import os
    import SimpleHTTPServer
    
    matrix.org's avatar
    matrix.org committed
    
    from daemonize import Daemonize
    
    
    Amber Brown's avatar
    Amber Brown committed
    
    
    class SimpleHTTPRequestHandlerWithPOST(SimpleHTTPServer.SimpleHTTPRequestHandler):
        UPLOAD_PATH = "upload"
    
        """
        Accept all post request as file upload
        """
    
    Amber Brown's avatar
    Amber Brown committed
    
    
        def do_POST(self):
    
            path = os.path.join(self.UPLOAD_PATH, os.path.basename(self.path))
    
    Amber Brown's avatar
    Amber Brown committed
            length = self.headers["content-length"]
    
    Amber Brown's avatar
    Amber Brown committed
            with open(path, "wb") as fh:
    
    Amber Brown's avatar
    Amber Brown committed
            self.send_header("Content-Type", "application/json")
    
            self.end_headers()
    
            # Return the absolute path of the uploaded file
            self.wfile.write('{"url":"/%s"}' % path)
    
    
    matrix.org's avatar
    matrix.org committed
    
    def setup():
        parser = argparse.ArgumentParser()
        parser.add_argument("directory")
        parser.add_argument("-p", "--port", dest="port", type=int, default=8080)
    
    Amber Brown's avatar
    Amber Brown committed
        parser.add_argument("-P", "--pid-file", dest="pid", default="web.pid")
    
    matrix.org's avatar
    matrix.org committed
        args = parser.parse_args()
    
        # Get absolute path to directory to serve, as daemonize changes to '/'
        os.chdir(args.directory)
        dr = os.getcwd()
    
    
    Amber Brown's avatar
    Amber Brown committed
        httpd = BaseHTTPServer.HTTPServer(("", args.port), SimpleHTTPRequestHandlerWithPOST)
    
    matrix.org's avatar
    matrix.org committed
    
        def run():
            os.chdir(dr)
            httpd.serve_forever()
    
        daemon = Daemonize(
    
    Amber Brown's avatar
    Amber Brown committed
            app="synapse-webclient", pid=args.pid, action=run, auto_close_fds=False
        )
    
    matrix.org's avatar
    matrix.org committed
    
        daemon.start()
    
    
    Amber Brown's avatar
    Amber Brown committed
    
    if __name__ == "__main__":
    
    matrix.org's avatar
    matrix.org committed
        setup()