random_str

privex.helpers.common.random_str(size: int = 50, chars: Sequence = 'abcdefhkmnprstwxyz23456789ACDEFGHJKLMNPRSTWXYZ')str[source]

Generate a random string of arbitrary length using a given character set (string / list / tuple). Uses Python’s SystemRandom class to provide relatively secure randomness from the OS. (On Linux, uses /dev/urandom)

By default, uses the character set SAFE_CHARS which contains letters a-z / A-Z and numbers 2-9 with commonly misread characters removed (such as 1, l, L, 0 and o). Pass ALPHANUM as chars if you need the full set of upper/lowercase + numbers.

Usage:

>>> from privex.helpers import random_str
>>> # Default random string - 50 character alphanum without easily mistaken chars
>>> password = random_str()
'MrCWLYMYtT9A7bHc5ZNE4hn7PxHPmsWaT9GpfCkmZASK7ApN8r'
>>> # Customised random string - 12 characters using only the characters `abcdef12345` 
>>> custom = random_str(12, chars='abcdef12345')
'aba4cc14a43d'

Warning: As this relies on the OS’s entropy features, it may not be cryptographically secure on non-Linux platforms:

> The returned data should be unpredictable enough for cryptographic applications, though its exact quality > depends on the OS implementation.

Parameters
  • size (int) – Length of random string to generate (default 50 characters)

  • chars (str) – Characterset to generate with ( default is SAFE_CHARS - a-z/A-Z/0-9 with often misread chars removed)