Search code examples
pythoncx-freezehttpserversimplehttpserver

Simple http Server does not work when converted to exe


I wrote a simple python http server to serve the files(folders) of the present working directory.

import socketserver
http=''
def httpServer(hostIpAddress):
  global  http
  socketserver.TCPServer.allow_reuse_address=True
  try:
    with  socketserver.TCPServer((hostIpAddress,22818),SimpleHTTPRequestHandler) as http:
       print(1123)
       http.serve_forever()
 except Exception as e:
     print(str(e))
       

if __name__ == '__main__':
     httpServer('192.168.1.2')      

this code works as expected .It serves the contents. However when i Freeze it (convert ist to executable) using cx-freeze . It does not serve the files .IN chrome it outs ERR_EMPTY_RESPONSE. I tried other browsers but to no avail.

My setup.py for the freeze is
executables = [
    Executable("test_http.py", base=base,target_name="test_http",shortcutName="test_http",shortcutDir="DesktopFolder")
]

setup(
    name="test_http",
    options={"build_exe":build_exe_option,"bdist_msi":bdist_msi_options},
    executables=executables
    )

The .exe works without any error and you can even see the program running in task manager. i used: cx-freeze(i tried version 6.6,6.7,6.8) python 3.7.7 32 bits os : windpows 8.1

Thanks in advance.


Solution

  • Instead of using a function httpserver , I used class and it build the exe without any problem and now the http server runs even in its executable form.

    Credit to: https://stackoverflow.com/users/642070/tdelaney for providing this solution at :

    https://pastebin.com/KsTmVWRZ

    import http.server
    import threading
    import functools
    import time
     
    # Example simple http server as thread
     
    class SilentHandler(http.server.SimpleHTTPRequestHandler):
        
        def log_message(self, format, *args, **kwargs):
            # do any logging you like there
            pass
        
    class MyHttpServerThread(threading.Thread):
        
        def __init__(self, address=("0.0.0.0",8000), target_dir="."):
            super().__init__()
            self.address = address
            self.target_dir = "."
            self.server = http.server.HTTPServer(address, functools.partial(SilentHandler, directory=self.target_dir))
            self.start()
     
        def run(self):
            self.server.serve_forever(poll_interval=1)
     
        def stop(self):
            self.server.shutdown() # don't call from this thread
            
    # test  
     
    if __name__ == "__main__":
        http_server = MyHttpServerThread()
        time.sleep(10)
        http_server.stop()
        print("done")