在使用Python请求运行后,如何从URL获取params?

时间:2016-12-11 23:18:34

标签: python http get python-requests

我知道如何使用当前的URL进行操作,例如

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

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

但是,如果您访问过网址后,例如带有OAuth的网址,例如

authorize_url = facebook.get_authorize_url(**params)
requests.get(authorized_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 个答案:

答案 0 :(得分:2)

您可以获取.url attribute from the Response object - 这将是最终响应网址:

$ ssh user@machine -t "/opt/ros/indigo/bin/activate && rostopic list"

然后,您可以urlparse提取GET参数的网址:

response = requests.get(authorized_url)
print(response.url)

答案 1 :(得分: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))