Unique session id in python

Viewed 43662

How do I generate a unique session id in Python?

5 Answers

You can use the uuid library like so:

import uuid
my_id = uuid.uuid1() # or uuid.uuid4()

Python 3.6 makes most other answers here a bit out of date. Versions including 3.6 and beyond include the secrets module, which is designed for precisely this purpose.

If you need to generate a cryptographically secure string for any purpose on the web, refer to that module.

https://docs.python.org/3/library/secrets.html

Example:

import secrets

def make_token():
    """
    Creates a cryptographically-secure, URL-safe string
    """
    return secrets.token_urlsafe(16)  

In use:

>>> make_token()
'B31YOaQpb8Hxnxv1DXG6nA'
import os, base64
def generate_session():
    return base64.b64encode(os.urandom(16))

It can be as simple as creating a random number. Of course, you'd have to store your session IDs in a database or something and check each one you generate to make sure it's not a duplicate, but odds are it never will be if the numbers are large enough.

Related