Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random filename-safe and URL-safe string

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?

like image 899
zakdances Avatar asked Jan 17 '12 16:01

zakdances


2 Answers

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('=', '')
like image 95
Chris Dutrow Avatar answered Sep 26 '22 06:09

Chris Dutrow


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

like image 39
rhymes Avatar answered Sep 22 '22 06:09

rhymes