9

I've created a system where users upload videos to my server's filesystem and I need a way to generate unique filenames for the video files. Should I be using random.getrandbits? Is there a way to do this with a combination of letters and numbers?

7
  • possible duplicate of stackoverflow.com/questions/2257441/… Commented Jan 17, 2012 at 16:53
  • 3
    What framework are you using? Often this is handled for you. What's wrong with the existing docs.python.org/library/tempfile.html library? Commented Jan 17, 2012 at 16:53
  • @S.Lott I don't think he wants to store the videos temporarily. Commented Jan 17, 2012 at 17:31
  • There's nothing "temporary" about the file names. They can be outside the /tmp filesystem. Commented Jan 17, 2012 at 18:00
  • 1
    I actually do want to store the videos temporarily...they should be able to be previewed (played back), then uploaded to youtube, then the original video should be deleted. Commented Jan 17, 2012 at 22:01

3 Answers 3

12

This is what I use:

import base64
import uuid

base64.urlsafe_b64encode(uuid.uuid4().bytes)

I generate a uuid, but I use the bytes instead of larger hex version or one with dashes. Then I encode it into a URL-safe base-64 string. This is a shorter length string than using hex, but using base64 makes it so that the characters in the string are safe for files, urls and most other things.

One problem is that even with the urlsafe_b64encode, it always wants to '='s signs onto the end which are not so url-safe. The '='s signs are for decoding the base-64 encoded information, so if you are only trying to generate random strings, then you can probably safey remove them with:

str.replace('=', '')
Sign up to request clarification or add additional context in comments.

3 Comments

This is EXACTLY what I needed right now; thanks! Just thought you'd want to know that your answer to a low-scoring question still helped a random guy on the Internet.
Thanks for the feedback. For us, its held up to the test of time so far, its almost a year later we still use this little snippit of code to generate primary keys throughout our entire application.
Noting that on Python 3 I had to include .decode('utf-8') to get a string to do replacement on: base64.urlsafe_b64encode(uuid.uuid4().bytes).decode('utf-8').replace('=', '')
9

You can use, in Python 3.6, the secrets module.

>>> import secrets
>>> secrets.token_urlsafe(8)
'Pxym7N2zJRs'

Further documentation is here: https://docs.python.org/3/library/secrets.html

Comments

3

Take a look at Universally unique identifiers (UUID) and Python's module uuid.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.