diff options
| author | Cody Logan <clpo13@gmail.com> | 2020-01-08 10:05:38 -0800 |
|---|---|---|
| committer | Cody Logan <clpo13@gmail.com> | 2020-01-08 10:05:38 -0800 |
| commit | f599b85ba5a5fe7123e0d77bf7b9f6c738471bc8 (patch) | |
| tree | f2c2be4d13df2ade7288dcf687dfb56d8993436e /alphanum/alphanum.py | |
| parent | 6c1a51693957ed491c16259746dd67c6c7c93f8a (diff) | |
| parent | 32060abca4e2e9c111d73b23f28f5837da41d7be (diff) | |
| download | alphanum-f599b85ba5a5fe7123e0d77bf7b9f6c738471bc8.tar.gz alphanum-f599b85ba5a5fe7123e0d77bf7b9f6c738471bc8.zip | |
Merge branch 'master' into sphinx-docs
Diffstat (limited to 'alphanum/alphanum.py')
| -rw-r--r-- | alphanum/alphanum.py | 37 |
1 files changed, 11 insertions, 26 deletions
diff --git a/alphanum/alphanum.py b/alphanum/alphanum.py index bb23cf5..6f7c103 100644 --- a/alphanum/alphanum.py +++ b/alphanum/alphanum.py @@ -1,13 +1,19 @@ -import random -import secrets +try: + import secrets as random +except ImportError: + import random import string POP = string.ascii_letters + string.digits def generate(length: int = 1) -> str: - """Generates a pseudo-random string of alphanumeric characters of the given - length. If no length is specified, a single character is returned. + """Generates a random string of alphanumeric characters of the given length + If no length is specified, a single character is returned. + + On Python 3.5, this string is pseudo-randomly generated using the random + module. With 3.6 and later, the randomness is generated with the secrets + module, making the randomization cryptographically strong. Args: length (:obj:`int`, optional): Desired string length. Defaults to 1. @@ -22,25 +28,4 @@ def generate(length: int = 1) -> str: 'a93jfDjdA0' """ - return ''.join(random.SystemRandom().choices(POP, k=length)) - - -def generate_s(length: int = 1) -> str: - """Generates a cryptographically strong random string of alphanumeric - characters of the given length. If no length is specified, a single - character is returned. - - Args: - length (:obj:`int`, optional): Desired string length. Defaults to 1. - - Returns: - str: A random alphanumeric string. - - Examples: - >>> print(alphanum.generate_s()) - '5' - >>> print(alphanum.generate_s(10)) - 't3g0Gh9Naj' - - """ - return ''.join(secrets.SystemRandom().choice(POP) for i in range(length)) + return ''.join(random.SystemRandom().choice(POP) for i in range(length)) |
