Python - 获取浏览器被重定向到的网址

标签 python redirect browser urllib2

我正在尝试使用 API 对应用程序进行身份验证。
方法如下:

  1. 我正在使用 webbrowser.open 打开一个 URL。
  2. 用户对应用程序进行身份验证,并被重定向到另一个 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)

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

最佳答案

尝试为一个请求启动您自己的小型 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()

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

关于Python - 获取浏览器被重定向到的网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15492917/

相关文章:

python - rpy2 中的错误 - 没有(非缺失)观察结果

python递归函数调用

javascript - 将leveldb数据库传输到浏览器

.htaccess - 如何重定向单个分割网址,但末尾没有正斜杠?

javascript - 浏览器是否会阻止多个同时异步 XMLHttpRequest 上的 JS 执行?

javascript - 在浏览器中直观地更改 URL

python - Scikit Learn 预测单个观察结果

python - 寻找不匹配模式的效率

php - 重定向时提供成功消息的最佳方式?

python - Django 将 URL 重定向到绝对 URL