Asp*_*pen 6 python get http python-requests
我知道如何使用当前 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,但是有没有更干净的方法呢?
完整代码如下:
索引.j2
<p><a href="/facebook-login">Login with Facebook</a></p>
路线.py
app.add_route('/facebook-login', LoginHandler('index.j2'))
app.add_route('/authorized', AuthorizedHandler('index.j2'))
处理程序.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)
.url您可以从Response对象获取属性- 这将是最终的响应 URL:
response = requests.get(authorized_url)
print(response.url)
然后,您可以urlparse从 url 中提取 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']}
| 归档时间: | 
 | 
| 查看次数: | 8509 次 | 
| 最近记录: |