我知道如何使用當前網址來完成此操作,例如如何在使用Python請求運行後從URL中獲取參數?
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)
可是你知道,如果你訪問一個URL,比如一個使用OAuth之後,例如
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)
這對我來說似乎完全合乎邏輯!不幸的是,response.url返回的響應是我的'REDIRECT_URI',在這裏是'https:// www.facebook.com/connect/login_success.html',而不是'code' param的URL尋找。 – Aspen
另一方面,當我添加'webbrowser.open(authorized_url)' – Aspen
@Adrienne問題時,地址欄中將顯示正確的URL,請您提供完整的代碼到目前爲止?我懷疑這可能是因爲你需要一個真正的瀏覽器才能進入重定向鏈結局,想要測試它。謝謝! – alecxe