How to run a http server which serves a specific path?

后端 未结 6 732
萌比男神i
萌比男神i 2020-12-02 12:02

this is my Python3 project hiearchy:

projet
  \\
  script.py
  web
    \\
    index.html

From script.py, I would like to run a

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 12:47

    In Python 3.7 SimpleHTTPRequestHandler can take a directory argument:

    import http.server
    import socketserver
    
    PORT = 8000
    DIRECTORY = "web"
    
    
    class Handler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=DIRECTORY, **kwargs)
    
    
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("serving at port", PORT)
        httpd.serve_forever()
    

    and from the command line:

    python -m http.server --directory web
    

    To get a little crazy... you could make handlers for arbitrary directories:

    def handler_from(directory):
        def _init(self, *args, **kwargs):
            return http.server.SimpleHTTPRequestHandler.__init__(self, *args, directory=self.directory, **kwargs)
        return type(f'HandlerFrom<{directory}>',
                    (http.server.SimpleHTTPRequestHandler,),
                    {'__init__': _init, 'directory': directory})
    
    
    with socketserver.TCPServer(("", PORT), handler_from("web")) as httpd:
        print("serving at port", PORT)
        httpd.serve_forever()
    

提交回复
热议问题