aboutsummaryrefslogtreecommitdiff
path: root/app/func/generate_api_key.py
blob: a40c96ab0db9b5f8d0e31299fb31ba785707e387 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import sqlalchemy
from sqlalchemy import exc
import random
import string

from db import engine

"""
Generate and return a randomized API key string for the user
Keys are composed of 20 uppercase ASCII characters
"""
def generate_api_key():
    with engine.begin() as conn:
        while True:
            try:
                api_key_string = ''.join(random.choices(string.ascii_uppercase, k=20))
                conn.execute(sqlalchemy.text('INSERT INTO keys(api_key) VALUES(:api_key)'), [{'api_key': api_key_string}])
                conn.commit()
                break
            except exc.IntegrityError:
                continue

    return api_key_string