如何使用Python requests运行URL后获取参数?

6

我知道如何使用当前URL来完成它,例如:

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)

但是如果你访问的一个URL,例如OAuth的URL之后,会发生什么呢?

authorize_url = facebook.get_authorize_url(**params)
requests.get(authorized_url)

URL将会指向类似于https://localhost:5000/authorized?code=AQCvF的地址。我如何获取code=AQCvF

我可能可以做一些事情,比如获取当前浏览器的地址,然后解析URL,但是有没有更简洁的方法呢?


完整的代码如下:

index.j2

<p><a href="/facebook-login">Login with Facebook</a></p>

routes.py

app.add_route('/facebook-login', LoginHandler('index.j2'))
app.add_route('/authorized', AuthorizedHandler('index.j2'))

handlers.py

from rauth.service import OAuth2Service
import requests
import os

# rauth OAuth 2.0 service wrapper
graph_url = 'https://graph.facebook.com/'
facebook = OAuth2Service(name='facebook',
                         authorize_url='https://www.facebook.com/dialog/oauth',
                         access_token_url=graph_url + 'oauth/access_token',
                         client_id=FB_CLIENT_ID,
                         client_secret=FB_CLIENT_SECRET,
                         base_url=graph_url)


class AuthorizedHandler(TemplateHandler):

    def on_get(self, req, res):
        code = self.requests.get['code']
        data = dict(code=code, redirect_uri=REDIRECT_URI)
        session = facebook.get_auth_session(data=data)

        # response
        me = session.get('me').json()
        print('me', me)

        UserController.create(me['username'], me['id'])


class LoginHandler(TemplateHandler):

    async def on_get(self, req, res):
        # visit URL and client authorizes
        params = {'response_type': 'code',
                  'redirect_uri': REDIRECT_URI}

        webbrowser.open(facebook.get_authorize_url(**params))

        response = requests.get(facebook.get_authorize_url(**params))
        print(response.url)
2个回答

8
您可以从Response对象中获取.url属性,这将是最终的响应URL。
response = requests.get(authorized_url)
print(response.url)

然后,您可以使用urlparse函数来提取GET参数:

In [1]: from urllib.parse import parse_qs, urlparse

In [2]: url = "https://localhost:5000/authorized?code=AQCvF"

In [3]: parse_qs(urlparse(url).query)
Out[3]: {'code': ['AQCvF']}

这对我来说完全合乎逻辑!不幸的是,response.url返回的响应是我的“REDIRECT_URI”,在这种情况下是“https://www.facebook.com/connect/login_success.html”,而不是我正在寻找的带有“code”参数的URL。 - Adrienne
另一方面,当我添加 webbrowser.open(authorized_url) 时,正确的URL将出现在地址栏中。 - Adrienne
1
@Adrienne,你能提供一下你目前的完整代码吗?我怀疑可能需要一个真正的浏览器才能到达重定向链的最终目标,想要测试一下。谢谢! - alecxe
当然,只需将其附加即可!是的,这也是我怀疑的。 - Adrienne
我怀疑缺少重定向与需要存储cookie的会话有关。但是 rauth 的文档建议我们可以从URL中获取code参数并将其传递到会话中,这似乎是相互矛盾的 (https://rauth.readthedocs.io/en/latest/) `# 代码应该在授权步骤的重定向后返回,

确保在此处使用它 (提示:它在URL中!)

session = facebook.get_auth_session(data={'code': 'foo', 'redirect_uri': redirect_uri})`
- Adrienne

1
如果您使用的是同步Python框架,那么您的代码应该可以正常工作;但是,根据 async def on_get(self, req, res),看起来您正在使用异步框架。
因此,您需要编写一个异步的HTTP请求函数,使用aiohttp.web,或者如果您的框架内置了这个函数,您可以将 requests.get(facebook.get_authorize_url(**params)) 替换为 res.redirect(facebook.get_authorize_url(**params))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接