Generate a password (or other secure token) using a pattern language similar to regular expressions. We'll use the strgen
module that enables a user to generate test data, unique ids, passwords, vouchers or other randomized data very quickly using a template language. The template language is superficially similar to regular expressions but instead of defining how to match or capture strings, it defines how to generate randomized strings.
1 2 | from strgen import StringGenerator as SG
SG("[\w\p\d]{20}").render()
|
The standard way to create a random string such as for use as a password in Python:
import random
import string
password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
Using strgen
, the equivalent is:
from strgen import StringGenerator as SG
SG('[\u\d]{10}').render()
What about the requirement - much more likely - "a password shall have 6 - 20 characters of which at least one must be a digit and at least one must be a special character":
SG("[\l\d]{4:18}&[\d]&[\p]").render()
You need to install the module:
pip install strgen
strgen
is better than the standard way:
- Less verbose
- Trivial editing of the pattern lets you incorporate additional important features (variable length, minimum length, additional character classes, etc.)
- Uses cryptographic-grade SystemRandom class (if available, or falls back to Random)
- Uses a pattern language superficially similar to regular expressions, so it's easy to learn
- Installs with pip
(Disclosure: I am the author of the strgen
module.)
Paul - ActiveState's site seems to be doing something with your link to pypi. But a copy/paste of the blue text worked fine.
Fixed the link to PyPi, which is also there:
https://pypi.python.org/pypi/StringGenerator/0.1.3