2016-12-11 32 views
2

我知道如何使用當前網址來完成此操作,例如如何在使用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) 

回答

1

你可以得到.url attribute from the Response object - 這將是最後響應網址:

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']} 
+0

這對我來說似乎完全合乎邏輯!不幸的是,response.url返回的響應是我的'REDIRECT_URI',在這裏是'https:// www.facebook.com/connect/login_success.html',而不是'code' param的URL尋找。 – Aspen

+0

另一方面,當我添加'webbrowser.open(authorized_url)' – Aspen

+1

@Adrienne問題時,地址欄中將顯示正確的URL,請您提供完整的代碼到目前爲止?我懷疑這可能是因爲你需要一個真正的瀏覽器才能進入重定向鏈結局,想要測試它。謝謝! – alecxe

1

如果您使用的是同步Python框架,則您的代碼可以正常工作,但看起來您使用的是異步框架工作,暗示async def on_get(self, req, res)

您將不得不編寫異步HTTP請求函數,使用aiohttp.web,或者您的框架可能內置了一個,並且您可以用res.redirect(facebook.get_authorize_url(**params))替換requests.get(facebook.get_authorize_url(**params))

+0

哦,很好的觀察,謝謝分享! – alecxe

相關問題