Generating Unique Keys

Skip Montanaro skip at
Sat Jan 25 18:39:47 CET 2003

    Mongryong> Right now, I mainly need a way to generate unique (web)
    Mongryong> session keys.  However, it would be nice to have a general
    Mongryong> purpose function for generating unique keys.

So just call random.random() until you get something not in your database:

    while 1:
        newkey = "%.f" % random.random()
        if newkey in db:

    Mongryong> For session keys, is their a way in Python to grap a client's
    Mongryong> MAC address.  If so, is there any security concern with using
    Mongryong> a client's MAC address?

There's no MAC address information in the HTTP headers.  There is the
client's IP address, but for proxies and NAT stuff that obviously won't be
good enough.  I'd just use a random number.

Also, make sure you store timestamps in your session database and purge old
session info periodically.  If you don't you will probably see your system
performance go to hell as the size of that table grows.


More information about the Python-list mailing list