views:

86

answers:

1

Facebook returns access tokens in the form of a string:

'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'

Is there a way to parse the access_token without using regex? I'm afraid using regex would be unaccurate since I don't know what FB uses as access tokens

I'm getting the result like this:

result=urlfetch.fetch(url="https://graph.facebook.com/oauth/access_token",payload=payload,method=urlfetch.POST)
result2=result.content
+2  A: 

Facebook access_token and expires are returned as key=value pairs. One way to parse them is to use the parse_qs function from the urlparse module.

>>> import urlparse
>>> s = 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'
>>> urlparse.parse_qs(s)
{'access_token': ['159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw'], 'expires': ['4375']}
>>> 

There is also parse_qsl should you wish to get the values as a list of tuples.

>>> urlparse.parse_qsl(s)
[('access_token', '159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw'), ('expires', '4375')]
>>> dict(urlparse.parse_qsl(s)).get('access_token')
'159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw'
>>> 
Manoj Govindan
Great! Although on appengine that I'm using, i had to import it from cgi