@@ -1863,13 +1863,28 @@ def base_decode(
18631863 return result
18641864
18651865
1866- def gen_id (rand_len = 4 ) -> str :
1867- """Generate a unique ID based on the current time and random bytes.
1866+ def gen_id (rand_len = 4 , sep = "_" ) -> str :
1867+ """Generate a readable & unique ID based on the current time(ms) and random bytes.
1868+ The performance is about 400000 IDs per second.
18681869
18691870 If rand_len=0 the length of ID will be 18, rand_len=4 the length of ID will be 22.
18701871 ID format:
18711872 - {YYMMDD_HHMMSS}_{4-digit base62 of microsecond}{rand_len urandom hex string}
18721873
1874+ The following table shows the relationship between rand_len and the safe range of unique IDs per microsecond:
1875+
1876+ rand_len | urandom_size | Safe Range
1877+ ---------------------------------------------
1878+ 2 | 1 | 10
1879+ 4 | 2 | 100
1880+ 6 | 3 | 1000
1881+ 8 | 4 | 10000
1882+ 10 | 5 | 100000
1883+ 12 | 6 | 1000000
1884+ 14 | 7 | 10000000
1885+
1886+ Seems like rand_len -> 10 ** (rand_len // 2) safe range.
1887+
18731888 Args:
18741889 rand_len (int, optional): Defaults to 4.
18751890
@@ -1886,15 +1901,17 @@ def gen_id(rand_len=4) -> str:
18861901 1000
18871902 >>> [len(gen_id(i)[:]) for i in range(10)]
18881903 [18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
1904+ >>> # gen_id() => 251111_235204_0xYfc4f8
1905+ >>> # gen_id(sep="") => 2511112352291nTq972c
18891906 """
18901907 now = datetime .now ()
1891- s1 = now .strftime ("%y%m%d_ %H%M%S" )
1908+ s1 = now .strftime (f "%y%m%d { sep } %H%M%S" )
18921909 s2 = base_encode (now .microsecond )
18931910 if rand_len :
18941911 s3 = os .urandom (rand_len // 2 + 1 ).hex ()[:rand_len ]
18951912 else :
18961913 s3 = ""
1897- return f"{ s1 } _ { s2 :>04} { s3 } "
1914+ return f"{ s1 } { sep } { s2 :>04} { s3 :0>{ rand_len } } "
18981915
18991916
19001917def timeti (
0 commit comments