Generating a short unique id in Python (similar to uniqid in PHP. Hey guys, I've done a bunch of Googling around and can't find a nice way to generate a unique id in Python similar to the uniqid function in PHP.
Generate randomized strings of characters using a template
Character sets used for backslashed character codes are exactly the Python character sets from the string package. While the module is designed to work on pre- Python 3, we use only those member variables from the string module that are present in Python 3. This avoids the locale-dependent sets of characters in Python 2.x.
Apr 06, 2020 Python UUID module to generate the universally unique identifiers. Generate a version 1, 3, 4, and 5 UUIDs. Secure random UUID. String to UUID and UUId to String. Why and when use UUID.Structure of UUID. Safe and Unsafe UUID.
Project description
Generate test data, unique ids, passwords, vouchers or other randomizedtextual data very quickly using a template language. The templatelanguage is superficially similar to regular expressions but instead ofdefining how to match or capture strings, it defines how to generaterandomized strings. A very simple invocation to produce a random stringwith word characters and digits of 10 characters length:
The purpose of this module is to save the Python developer from havingto write verbose code around the same pattern every time to generatepasswords, keys, tokens, test data, etc. of this sort:
that is:
Hard to read even at this simplistic level.
Hard to safely change quickly. Even modest additions to therequirements need unreasonably verbose solutions.
Doesn’t use safe encryption standards.
Doesn’t provide the implied minimal guarantees of characteroccurance.
Hard to track back to requirements (“must be between x and y inlength and have characters from sets Q, R and S”).
The template uses short forms similar to those of regular expressions.An example template for generating a strong password:
will generate something like the following:
Guarantee at least two “special” characters in a string:
You can also generate useful test data, like fake emails with plenty ofvariation:
Installation
Install as standard for Python packages from PyPi:
Usage
or to produce a list of unique strings:
Example:
The template is a string that is a sequence of one or more of thefollowing:
Literal text (for example: UID)
Character class (for example: [a-zs])
Group, a combination of literals and character classes, possiblyseparated by operators and using parentheses where appropriate (forexample: (UID[d]{4}&[w]{4}))
In more detail:
Literal: <any string>
Any literal string.
Example:
Special characters need to be escaped with backslash .
Character class: [<class specification>]
Much like in regular expressions, it uses strings of characters andhyphen for defining a class of characters.
Example:
The generator will randomly choose characters from the set of lower caseletters, digits and the underscore. The number of characters generatedwill be exactly one in this case. For more, use a quantifier:
As a shortcut for commonly used character sets, a character set code maybe used. The following will render in exactly the same way:
Character Set Codes
W: whitespace + punctuation
a: ascii_letters
c: lowercase
d: digits
h: hexdigits
l: letters
o: octdigits
p: punctuation
r: printable
s: whitespace
u: uppercase
w: _ + letters + digits
Quantifier: {x:y}
Where x is lower bound and y is upper bound. This construct must alwaysfollow immediately a class with no intervening whitespace. It ispossible to write {:y} as a shorthand for {0:y} or {y} to indicate afixed length.
Example:
Generates a string from zero to 8 in length composed of lower casealphabetic characters.
Generates a string with either four lower case alphabetic characters ora string of digits that is four in length.
Using a character class and no quantifier will result in a quantifier of1. Thus:
will result always in either a, b, or c.
Variable Substitution
We provide the ${varname} syntax to enable any value to be returned.varname must be provided as a keyword argument to the render()or render_list() methods. You can use a list, function, generator.Here’s an example using a list:
Or use a range converted to a list:
Note that in Python 2.x range() returns a list. In Python 3,range() returns a range type.
Or using a function:
You can obviously pass any callable or generator that might, forinstance, randomly choose a value from a database, if that is what youwant.
Note there is a difference in handling between a callable and list type.If you use a list, StringGenerator picks an item from the list foryou, randomly. If you use a callable, StringGenerator takes and insertswhatever is returned by the callable. The callable is required to do anyrandomisation if that is what the user wants. So, if you pass a functionthat returns a list, the entire list will be inserted as a string.
Group: (<group specification>)
A group specification is a collection of literals, character classes orother groups divided by the OR operator or the shuffle operator&.
OR Operator
The binary operator can be used in a group to cause one of theoperands to be returned and the other to be ignored with an even chance.
Shuffle Operator
The binary & operator causes its operands to be combined andshuffled. This addresses the use case for many password requirements,such as, “at least 6 characters where 2 or more are digits”. Forinstance:
If a literal or a group is an operand of the shuffle operator, it willhave its character sequence shuffled with the other operand.
will produce strings like:
Concatenation and Operators
Classes, literals and groups in sequence are concatenated in the orderthey occur. Use of the or & operators always binds theoperands immediately to the left and right:
produces something like:
In other words, the digits occur first in sequence as expected. This isequivalent to this:
Special Characters, Escaping and Errors
There are fewer special characters than regular expressions:
They can be used as literals by escaping with backslash. All othercharacters are treated as literals. The hyphen is only special in acharacter class, when it appears within square brackets.
One special case is the escape character itself, backslash ’’. To escapethis, you will need at least two backslashes to escape it. So, threealltogether: one for Python’s string interpretation and one forStringGenerator’s escaping. If for some exotic reason you want twoliteral backslashes in a row, you need a total of eight backslashes. Theforegoing presupposes the template is a string in a file. If you areusing the template in a shell command line or shell script, you’ll needto make any changes required by your specific shell.
The template parser tries to raise exceptions when syntax errors aremade, but not every error will be caught, like having space between aclass and quantifier.
Spaces
Do not use any spaces in the template unless you intend to use them ascharacters in the output:
Character Classes and Quantifiers
Use a colon in the curly braces to indicate a range. There are sensibledefaults:
As of version 0.1.7, quantifier ranges can alternatively be specifiedwith a hyphen:
Here’s an example of generating a syntactically valid but, hopefully,spurious email address:
The first name will be exactly 10 lower case characters; the last namewill be 5-10 characters of lower case letters, each separated by eithera dot or underscore. The domain name without domain class will be 3 - 12lower case characters and the domain type will be one of‘.com’,‘.net’,‘.org’.
The following will produce strings that tend to have more letters,because the set of letters (52) is larger than the set of digits (10):
Windows 8 pro license key generator. Using multiple character set codes repeatedly will increase theprobability of a character from that set occuring in the result string:
This will provide a string that is three times more likely to contain adigit than the previous example.
Uniqueness
When using the unique=True flag in the render_list() method,it’s possible the generator cannot possibly produce the required numberof unique strings. For instance:
This will generate an exception but not before attempting to generatethe strings.
The number of times the generator needs to render new strings to satisfythe list length and uniqueness is not determined at parse time. Themaximum number of times it will try is by default n x 10 where n is therequested length of the list. Therefore, taking the above example, thegenerator will attempt to generate the unique list of 0’s and 1’s 100 x10 = 1000 times before giving up.
Progress
Generate Random Id Python
When using the progress_callback parameter of the render_list()method, it’s possible to inform others about the progress of stringgeneration. This is especially useful when generating a large number ofstrings.
The callback function obtains two int parameters: (current, total),which define the current progress and the total amount of requestedstrings.
By using that, callers of render_list() are able to implement aprogress indicator suitable for informing end users about the progressof string generation.
Unicode
Unicode is supported for both the template and output.
Character Sets
Unique Character Traits
Character sets used for backslashed character codes are exactly thePython character sets from the string package. While the module isdesigned to work on pre- Python 3, we use only those member variablesfrom the string module that are present in Python 3. This avoids thelocale-dependent sets of characters in Python 2.x.
Randomness Methods
The generator tries to use random.SystemRandom() for randint,shuffle, etc. It falls back to random.randint and associatedmethods if it can’t use SystemRandom.
Debugging
Call the dump() method on the class instance to get useful information:
Version of strgen module
Version of Python
The class name used for random methods
The parse tree
The output from one invocation of the render() method
The output looks something like the following:
Rationale and Design Goals
In Python, the need to generate random strings comes up frequently andis accomplished usually (though not always) via something like thefollowing code snippet:
This generates a string that is 10 characters made of uppercase lettersand digits. Unfortunately, this solution becomes cumbersome whenreal-world requirements are added. Take for example, the typicalrequirement to generate a password: “a password shall have 6 - 20characters of which at least one must be a digit and at least one mustbe a special character”. The above solution then becomes much morecomplicated and changing the requirements is an error-prone andunnecessarily complex task.
The equivalent using the strgen package:
strgen is far more compact, flexible and feature-rich than using thestandard solution:
It tries to use a better entropy mechanism and falls back gracefullyif this is not available on the host OS.
The user can easily modify the specification (template) with minimaleffort without the fear of introducing hard-to-test code paths.
It covers a broader set of use cases: unique ids, persistent uniquefilenames, test data, etc.
The template syntax is easy to learn for anyone familiar with regularexpressions while being much simpler.
It supports unicode.
It works on Python 2.6, 2.7 and 3.x.
It proposes a standard way of expressing common requirements, like “apassword shall have 6 - 20 characters of which at least one must be adigit and at least one must be a special character”:
This package is designed with the following goals in mind:
Provide an abstract template language that does not depend on aspecific implementation language.
Reduce dependencies on other packages.
Keep syntax as simple as possible while being useful.
Provide an implementation design with associated behaviour thatstrikes the right balance between ease-of-implementation andease-of-use.
Superficially similar to regular expressions to enable developers toquickly pick up the template syntax.
Support non-ASCII languages (unicode).
Testing
For running the unit tests, you might want to try:
Acknowledgements
Thanks to Robert LeBlanc who caught some important errors in escapingspecial characters. Thanks to Andreas Motl for the progress counter.
Original Author: paul.wolf@yewleaf.com
Release historyRelease notifications
0.3.3
0.3.2
0.3.1
0.3.0
0.2.1
0.2.0
0.1.9
0.1.8
0.1.7
0.1.6
0.1.5
0.1.4
0.1.3
0.1.2
0.1.1
0.1
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Unique keys add a layer of data integrity to an Azure Cosmos container. You create a unique key policy when you create an Azure Cosmos container. With unique keys, you make sure that one or more values within a logical partition is unique. You also can guarantee uniqueness per partition key.
After you create a container with a unique key policy, the creation of a new or an update of an existing item resulting in a duplicate within a logical partition is prevented, as specified by the unique key constraint. The partition key combined with the unique key guarantees the uniqueness of an item within the scope of the container.
Python Generate A Unique Character Keys
For example, consider an Azure Cosmos container with email address as the unique key constraint and CompanyID as the partition key. When you configure the user's email address with a unique key, each item has a unique email address within a given CompanyID. Two items can't be created with duplicate email addresses and with the same partition key value.
To create items with the same email address, but not the same first name, last name, and email address, add more paths to the unique key policy. Instead of creating a unique key based on the email address only, you also can create a unique key with a combination of the first name, last name, and email address. This key is known as a composite unique key. In this case, each unique combination of the three values within a given CompanyID is allowed.
For example, the container can contain items with the following values, where each item honors the unique key constraint.
CompanyID
First name
Last name
Email address
Contoso
Gaby
Duperre
gaby@contoso.com
Contoso
Gaby
Duperre
gaby@fabrikam.com
Fabrikam
Gaby
Duperre
gaby@fabrikam.com
Fabrikam
Ivan
Duperre
gaby@fabrikam.com
Fabrkam
Duperre
gaby@fabraikam.com
Fabrkam
gaby@fabraikam.com
If you attempt to insert another item with the combinations listed in the previous table, you receive an error. The error indicates that the unique key constraint wasn't met. You receive either Resource with specified ID or name already exists or Resource with specified ID, name, or unique index already exists as a return message.
Python Generate A Unique Character Key Generator
Define a unique key
You can define unique keys only when you create an Azure Cosmos container. A unique key is scoped to a logical partition. In the previous example, if you partition the container based on the ZIP code, you end up with duplicated items in each logical partition. Consider the following properties when you create unique keys:
You can't update an existing container to use a different unique key. In other words, after a container is created with a unique key policy, the policy can't be changed.
To set a unique key for an existing container, create a new container with the unique key constraint. Use the appropriate data migration tool to move the data from the existing container to the new container. For SQL containers, use the Data Migration tool to move data. For MongoDB containers, use mongoimport.exe or mongorestore.exe to move data.
A unique key policy can have a maximum of 16 path values. For example, the values can be /firstName, /lastName, and /address/zipCode. Each unique key policy can have a maximum of 10 unique key constraints or combinations. The combined paths for each unique index constraint must not exceed 60 bytes. In the previous example, first name, last name, and email address together are one constraint. This constraint uses 3 out of the 16 possible paths.
When a container has a unique key policy, Request Unit (RU) charges to create, update, and delete an item are slightly higher.
Sparse unique keys are not supported. If some unique path values are missing, they're treated as null values, which take part in the uniqueness constraint. For this reason, there can be only a single item with a null value to satisfy this constraint.
Unique key names are case-sensitive. For example, consider a container with the unique key constraint set to /address/zipcode. If your data has a field named ZipCode, Azure Cosmos DB inserts 'null' as the unique key because zipcode isn't the same as ZipCode. Because of this case sensitivity, all other records with ZipCode can't be inserted because the duplicate 'null' violates the unique key constraint.
Python Generate A Unique Character Keyboard
Next steps
Python Generate Guid
Learn more about logical partitions
Explore how to define unique keys when creating a container