Search code examples
pythondjangomixpanel

Python / Django: Get var from cookies


I tried to get distinct_id with request.COOKIES.get('distinct_id'). However Mixpanel saves the data in a not extractable way for me. Anyone knows why there are all these %22%3A%20%22 and how to extraxt distinct_id?

print(request.COOKIES):

{
'djdt': 'hide',
'cookie_bar': '1',
'mp_1384c4d0e46aaaaad007e3d8b5d6eda_mixpanel': '%7B%22distinct_id%22%3A%20%22165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22__alias%22%3A%20%22maz%2B1024%40gmail.com%22%7D',
'csrftoken': 'nvWzsrp3t6Sivkrsyu0gejjjjjiTfc36ZfkH7U7fgHaI40EF',
'sessionid': '7bkel6r27ebd55x262cv9lzv61gzoemw'
}

Solution

  • Check this code. You can run it because use the example you shared. First you must unquote the data in the mixpanel value. I used the suffix of the cookie key to get it. Then after the unquote you must load the json to get back a dictionary.

    The code here prints all the keys in the dictionary, but you can easily get the distinct_id using mixpanel_dict.get('distinct_id')

    Try it.

    from urllib import parse
    import json
    
    cookie = {'djdt': 'hide',
    'cookie_bar': '1',
    'mp_1384c4d0e46aaaaad007e3d8b5d6eda_mixpanel': '%7B%22distinct_id%22%3A%20%22165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22__alias%22%3A%20%22maz%2B1024%40gmail.com%22%7D',
    'csrftoken': 'nvWzsrp3t6Sivkrsyu0gejjjjjiTfc36ZfkH7U7fgHaI40EF',
    'sessionid': '7bkel6r27ebd55x262cv9lzv61gzoemw'
    }
    
    
    def get_value_for_mixpanel(cookie):
        mixpanel_dict = {}
        for key in cookie.keys():
            if '_mixpanel' in key:
                value = parse.unquote(cookie.get(key))
                mixpanel_dict = json.loads(value)
        return mixpanel_dict
    
    if __name__ == "__main__":
        mixpanel_dict = get_value_for_mixpanel(cookie) # type: dict
        for key,value in mixpanel_dict.items():
            print("%s:%s" %(key, value))
    

    Result

    distinct_id:165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b
    $initial_referrer:$direct
    $initial_referring_domain:$direct
    __alias:maz+1024@gmail.com