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?
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('=', '')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With