Unique session id in python

How do I generate a unique session id in Python?

Asked by: Brooke580 | Posted: 06-12-2021

Answer 1

UPDATE: 2016-12-21

A lot has happened in a the last ~5yrs. /dev/urandom has been updated and is now considered a high-entropy source of randomness on modern Linux kernels and distributions. In the last 6mo we've seen entropy starvation on a Linux 3.19 kernel using Ubuntu, so I don't think this issue is "resolved", but it's sufficiently difficult to end up with low-entropy randomness when asking for any amount of randomness from the OS.

I hate to say this, but none of the other solutions posted here are correct with regards to being a "secure session ID."

# pip install M2Crypto
import base64, M2Crypto
def generate_session_id(num_bytes = 16):
    return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes))

Neither uuid() or os.urandom() are good choices for generating session IDs. Both may generate random results, but random does not mean it is secure due to poor entropy. See "How to Crack a Linear Congruential Generator" by Haldir or NIST's resources on Random Number Generation. If you still want to use a UUID, then use a UUID that was generated with a good initial random number:

import uuid, M2Crypto
uuid.UUID(bytes = M2Crypto.m2.rand_bytes(num_bytes)))
# UUID('5e85edc4-7078-d214-e773-f8caae16fe6c')


# pip install pyOpenSSL
import uuid, OpenSSL
uuid.UUID(bytes = OpenSSL.rand.bytes(16))
# UUID('c9bf635f-b0cc-d278-a2c5-01eaae654461')

M2Crypto is best OpenSSL API in Python atm as pyOpenSSL appears to be maintained only to support legacy applications.

Answered by: Elise203 | Posted: 07-01-2022

Answer 2

You can use the uuid library like so:

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

Answered by: Max247 | Posted: 07-01-2022

Answer 3

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.



import secrets

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

In use:

>>> make_token()

Answered by: Hailey429 | Posted: 07-01-2022

Answer 4

import os, base64
def generate_session():
    return base64.b64encode(os.urandom(16))

Answered by: Miller163 | Posted: 07-01-2022

Answer 5

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.

Answered by: Chester226 | Posted: 07-01-2022

Similar questions

python - Django session expiry?

From django's documentation, I became under the impression that calling: request.session.set_expiry(300) From one view would cause the session to expire after five minutes inactivity; however, this is not the behavior that I'm experiencing in django trunk. If I call this method from one view, and browse around to other views that don't call the m...

python - Losing session data when user logs in

I have been working on a shop that is built in Python on the back of the django framework, everything was working fine until I noticed that when a user proceeds to the checkout and is requested to log in they do so and their basket empties...obvioulsy this is not a great thing for a basket to do, I was wondering what is causing this, could some look over my code and give me some advice at what it could be? I am at my wits...

Session in python?

Does Python have a session feature or not? If it does, then how can I use this and which library should I use?

php - How can I use python to load a browser session that posts values to a url?

I have a python script that takes a number of variables. I also have a html page that can receive post values. How can I start a browser from python and point it to the html page I have above and send those post variables to the html url? The problem I have is that if I use urllib/urllib2 to do the post, it doesn't load the browser window. And if I want to load a browser window I cannot send a post to the u...

Python SESSION (like php) class

is there any class to handle a SESSION (like php) in Python? not in django, but I want to use it with PyQt thank you

python - Check if Session Key is set

I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there any way to check if a session is set, so that it can be set if it doesn't exist?

python - How do I set a session to expire within 4 minutes?

Suppose I do this: request.session['x'] = 33 How do I make this session variable expire in 4 minutes? This variable only!! I don't want all the sessions to expire. If this cannot be done, is there a function that can keep track of it? (a function that uses sessions itself to count?)

python - Django & twill - session cookies not being set

I'm testing a django application with twill, and django-test-utils, and it's not logging me in. I think it's not setting the django session cookie. I go to a webpage (in twill) that calls request.session.set_test_cookie(), and after that call returns, twill.show_co...

python - django cached session

I have two questions: 1) I am wondering whether using django.contrib.sessions.backends.cache for storing sessions really improves performance of a website? Assuming there are around 25k simultaneous users. Each user making many database changes (for example browser game). Is the difference even noticable? 2) Again while using cached session (without db): how to check wheth...

python - django one session per user

based on docs ( http://docs.djangoproject.com/en/1.1/topics/http/sessions/ ) (yes - 1.1) Django creates unique sessions to all users. Logged user contains _auth_user_id. How can i achieve such check in login: If new_login._auth_user_id in database: delete(sessions_containing_same_id_except_new_one)

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python