-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added max attempts to create unique random key
- Loading branch information
1 parent
d84baf7
commit c49c63a
Showing
3 changed files
with
19 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,20 @@ | ||
import string | ||
import secrets | ||
|
||
from sqlalchemy.orm import Session | ||
|
||
from . import crud | ||
|
||
|
||
def create_random_key(length: int = 4) -> str: | ||
chars = string.ascii_lowercase + string.digits | ||
return "".join(secrets.choice(chars) for _ in range(length)) | ||
|
||
|
||
def create_unique_random_key(db: Session) -> str: | ||
ATTEMPTS = 10 | ||
for _ in range(ATTEMPTS): | ||
key = create_random_key() | ||
if crud.get_db_paste_by_key(db, key) is None: | ||
return key | ||
raise RuntimeError(f"Failed to generate unique random key in {ATTEMPTS}attempts.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters