Search code examples
pythondjangopython-social-auth

Can't access to python social auth's data


I am using Django 1.9.5 and have a problem with the data that python social auth gives. I got the data, but I cant' access it. This is my code

def save_auth_data_session(request):
    if request.user:
        twitter =  request.user.social_auth.get(provider ='twitter')
        print twitter.extra_data['access_token']

The terminal gives me this error

""TypeError: string indices must be integers""

If I do a "print vars(twitter)", this the data I get

{'user_id': 123, 'uid': u'2413671427750', '_user_cache': <User: quintana>, '_state': <django.db.models.base.ModelState object at 0x7fa3d86fc2d0>, 'provider': u'twitter', 'extra_data': u'{"access_token": {"oauth_token_secret": "Afkasdasdas21zxbxcbn", "oauth_token": "2468cxcpqsldkenI56", "x_auth_expires": "0", "user_id": "455793463", "screen_name": "puertoRico"}, "id": 455793463}', 'id': 123}

Solution

  • As i can see from output of print vars(twitter) - extra_data stores serialized dictionary (string) 'extra_data': u'{...}'.

    So you need to deserialize it first.

    import json
    
    twitter =  request.user.social_auth.get(provider ='twitter')
    extra_data = json.loads(twitter.extra_data)  # will give you a python dictionary
    print extra_data['access_token']