• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import os, random
2
3
4def unique_id(cookie_key):
5    """
6    Find out if remote caller has cookie set on the key.
7    If not, set cookie on client side: evaluate this key by a random string.
8    ( unique user identifier )
9    In both scenarios return value of the cookie, be it old or newly set one
10    """
11    uid = ''
12    ## try to retrieve uid from Cookie
13    if 'HTTP_COOKIE' in os.environ:
14        ## parse os.environ['HTTP_COOKIE']
15        cookies = os.environ['HTTP_COOKIE'].split(';')
16        key = '%s=' % cookie_key
17        uid_cookies = [c for c in cookies if c.strip().startswith(key)]
18
19        if uid_cookies:
20            assert(len(uid_cookies) == 1)
21            uid_cookie = uid_cookies[0]
22            uid = uid_cookie.replace(key, '')
23
24    if not uid:
25        uid = str(random.random())[2:16] # random string of 14 digits
26        set_cookie_statement = 'Set-Cookie:%s=%s;' % (cookie_key, uid)
27        set_cookie_statement += 'expires=Thu, 26-Dec-2013 22:03:25 GMT;'
28        print set_cookie_statement
29
30    return uid
31