Load a URL in the browser from Python

360 views Asked by At

I am writing a class which will authorize access to the ETrade API. (In theory this will actually be able to work with any API which uses OAuth 1.0.) The full code can be found in my GitHub. The relevant code to my question follows:

base_url = 'https://etws.etrade.com'


class Authorization:
    def __init__(self):
        self.oauth_session = requests_oauthlib.OAuth1Session(config.oauth_consumer_key, config.consumer_secret,
                                                             callback_uri='oob')
        self.oauth_url = base_url + "/oauth"
        print(self.get_authorization_url())
        self.run_authorization_server()

    // ... snip ...

    def run_authorization_server(self):
        host_name = 'localhost'
        host_port = 80
        with server.HTTPServer((host_name, host_port), AuthenticationCallbackHandler) as httpd:
            httpd.serve_forever()

As you can see, I print the authorization URL and the user must copy and paste it to their browser. When I run in IntelliJ IDEA, it is parsed in the console and I can click on it. This URL will load a page for the user to log in to their account and authorize my app to gain access. The result comes back as a reply to http://localhost. This is why I start an instance of HTTPServer to listen for the request with the verification token.

This process is less than ideal. I want to load the authorization URL programmatically. The complication is that I need to ensure that my local server starts before loading the authorization. As far as I can tell, server_forever() blocks the current thread. This suggests that I will need to start a thread to spin up the server. How do I do this? And more importantly, how do I tell that the server has started so that it is safe to load the URL? And finally, how do I actually load the URL in a browser?

1

There are 1 answers

0
Nijan On

You can use import select and .poll() to check if the socket object is alive.

You can then use webbrowser to open the URl: https://docs.python.org/2/library/webbrowser.html#module-webbrowser

webbrowser.open_new_tab(self.get_authorization_url())