Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for listening on random port and opening browser without delays #214

Open
spanezz opened this issue Nov 23, 2019 · 0 comments
Open
Labels
type: feature A self-contained enhancement or new feature

Comments

@spanezz
Copy link

spanezz commented Nov 23, 2019

Hello,

I wanted to support opening a browser on a random local port, and got it working with a bit of monkeypatching:

        server = make_server(…)
                
        import tornado.web
        import tornado.httpserver
        import tornado.netutil                   
        import webbrowser
                    
        class Application(tornado.web.Application):
            def listen(self, *args, **kw):
                sockets = tornado.netutil.bind_sockets(0, 'localhost')
                server = tornado.httpserver.HTTPServer(self)
                server.add_sockets(sockets)
                pairs = []
                for s in sockets:        
                    pairs.append(s.getsockname()[:2])
                pairs.sort()
                host, port = pairs[0]
                if ":" in host:    
                    host = f"[{host}]"    
                url = f"http://{host}:{port}"    
                log.info("Listening on %s", url)    
        
                async def open_browser():        
                    webbrowser.open_new_tab(url)     
 
                tornado.ioloop.IOLoop.current().add_callback(open_browser)    
                return server

        # Monkey patch to be able to start servers in a smoother way that the
        # defaults of livereload
        import livereload.server
        livereload.server.web.Application = Application
        server.serve()

Integrating this in livereload seems to require some refactoring of how the server is started, and I didn't engage on it. I hope that my monkeypatched code can be a useful reference.

Ideally, I would have liked to be able to subclass Server or the Application used by server, and have enough hooks to intervene in the listening bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: feature A self-contained enhancement or new feature
Projects
None yet
Development

No branches or pull requests

2 participants