Python - Getting url a browser was redirected to

后端 未结 2 773
北荒
北荒 2021-02-06 17:17

I am trying to authenticate an application with the API.
Here\'s How:

  1. I am opening a URL using webbrowser.open.
  2. The user authenticates
2条回答
  •  灰色年华
    2021-02-06 17:58

    Try to fire up your own little HTTP server for just one request, let the API redirect to it and wait for the redirected request to appear. This is not a complete example, just the basic concept:

    import BaseHTTPServer
    auth_url = 'https://stackexchange.com/oauth/dialog'
    
    # replace with your own http handlers
    def wait_for_request(server_class=BaseHTTPServer.HTTPServer,
                         handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
        server_address = ('', 8000)
        httpd = server_class(server_address, handler_class)
        return httpd.handle_request()
    
    def authenticate():
        scope = "write_access,private_info,read_inbox"
        url = make_url(auth_url,client_id=132,
                       scope=scope,response_type='code',
                       redirect_uri='http://localhost:8000/login_success')
        webbrowser.open(url)
        wait_for_request()
    

    You probably need to use HTTPS though. In the long run, you might be better off with an existing OAuth implementation.

提交回复
热议问题