<s> from psycopg2 import IntegrityError <EOL> import random <EOL> class FailedToReserveUsername ( Exception ) : pass <EOL> class RanOutOfUsernameAttempts ( Exception ) : pass <EOL> def gen_random_usernames ( ) : <EOL> """<STR_LIT>""" <EOL> while <NUM_LIT:1> : <EOL> yield hex ( int ( random . random ( ) * <NUM_LIT:16> ** <NUM_LIT:12> ) ) [ <NUM_LIT:2> : ] . zfill ( <NUM_LIT:12> ) . decode ( '<STR_LIT>' ) <EOL> def insert_into_participants ( cursor , username ) : <EOL> return cursor . one ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> , ( username , username . lower ( ) ) <EOL> ) <EOL> def safely_reserve_a_username ( cursor , gen_usernames = gen_random_usernames , <EOL> reserve = insert_into_participants ) : <EOL> """<STR_LIT>""" <EOL> cursor . execute ( "<STR_LIT>" ) <EOL> seatbelt = <NUM_LIT:0> <EOL> for username in gen_usernames ( ) : <EOL> seatbelt += <NUM_LIT:1> <EOL> if seatbelt > <NUM_LIT:100> : <EOL> raise FailedToReserveUsername <EOL> try : <EOL> check = reserve ( cursor , username ) <EOL> except IntegrityError : <EOL> cursor . execute ( "<STR_LIT>" ) <EOL> continue <EOL> else : <EOL> assert check == username <EOL> break <EOL> else : <EOL> raise RanOutOfUsernameAttempts <EOL> cursor . execute ( "<STR_LIT>" ) <EOL> return username </s>
