Hashes and restores values using the "hashids" algorithm.
| 163 | |
| 164 | |
| 165 | class Hashids(object): |
| 166 | """Hashes and restores values using the "hashids" algorithm.""" |
| 167 | ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' |
| 168 | |
| 169 | def __init__(self, salt='', min_length=0, alphabet=ALPHABET): |
| 170 | """ |
| 171 | Initializes a Hashids object with salt, minimum length, and alphabet. |
| 172 | |
| 173 | :param salt: A string influencing the generated hash ids. |
| 174 | :param min_length: The minimum length for generated hashes |
| 175 | :param alphabet: The characters to use for the generated hash ids. |
| 176 | """ |
| 177 | self._min_length = max(int(min_length), 0) |
| 178 | self._salt = salt |
| 179 | |
| 180 | separators = ''.join(x for x in 'cfhistuCFHISTU' if x in alphabet) |
| 181 | alphabet = ''.join(x for i, x in enumerate(alphabet) |
| 182 | if alphabet.index(x) == i and x not in separators) |
| 183 | |
| 184 | len_alphabet, len_separators = len(alphabet), len(separators) |
| 185 | if len_alphabet + len_separators < 16: |
| 186 | raise ValueError('Alphabet must contain at least 16 ' |
| 187 | 'unique characters.') |
| 188 | |
| 189 | separators = _reorder(separators, salt) |
| 190 | |
| 191 | min_separators = _index_from_ratio(len_alphabet, RATIO_SEPARATORS) |
| 192 | |
| 193 | number_of_missing_separators = min_separators - len_separators |
| 194 | if number_of_missing_separators > 0: |
| 195 | separators += alphabet[:number_of_missing_separators] |
| 196 | alphabet = alphabet[number_of_missing_separators:] |
| 197 | len_alphabet = len(alphabet) |
| 198 | |
| 199 | alphabet = _reorder(alphabet, salt) |
| 200 | num_guards = _index_from_ratio(len_alphabet, RATIO_GUARDS) |
| 201 | if len_alphabet < 3: |
| 202 | guards = separators[:num_guards] |
| 203 | separators = separators[num_guards:] |
| 204 | else: |
| 205 | guards = alphabet[:num_guards] |
| 206 | alphabet = alphabet[num_guards:] |
| 207 | |
| 208 | self._alphabet = alphabet |
| 209 | self._guards = guards |
| 210 | self._separators = separators |
| 211 | |
| 212 | # Support old API |
| 213 | self.decrypt = _deprecated(self.decode, "decrypt") |
| 214 | self.encrypt = _deprecated(self.encode, "encrypt") |
| 215 | |
| 216 | def encode(self, *values): |
| 217 | """Builds a hash from the passed `values`. |
| 218 | |
| 219 | :param values The values to transform into a hashid |
| 220 | |
| 221 | >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') |
| 222 | >>> hashids.encode(1, 23, 456) |
no outgoing calls