Python - 获取浏览器重定向到的url

pra*_*nsg 5 python browser redirect urllib2

我正在尝试使用 API 验证应用程序。
就是这样:

  1. 我正在使用打开一个 URL webbrowser.open
  2. 用户对应用程序进行身份验证,并被重定向到另一个 URL,该 URL
    https://stackexchange.com/oauth/login_success包含用此 URL 编码的参数。
    重定向 URL 示例为:
    .../login_success#access_token=xyz&expires=00000

我当前的代码:

auth_url = 'https://stackexchange.com/oauth/dialog'
def authenticate():
    scope = "write_access,private_info,read_inbox"
    url = make_url(auth_url,client_id=132,
                   scope=scope,response_type='code',
                   redirect_uri='https://stackexchange.com/oauth/login_success')
    webbrowser.open(url)
Run Code Online (Sandbox Code Playgroud)

用户验证自己身份后如何获取重定向 URL(用户被带到的 URL)???

svc*_*ckr 3

尝试仅针对一个请求启动您自己的小型 HTTP 服务器,让 API 重定向到它并等待重定向的请求出现。这不是一个完整的示例,只是基本概念:

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()
Run Code Online (Sandbox Code Playgroud)

不过,您可能需要使用 HTTPS。从长远来看,使用现有的 OAuth 实现可能会更好。