Skip to content
Advertisement

Flask-Sqlalchemy : How to call a function everytime a new instance of a model is commited?

I want to make a new randomized user id every time a new user is committed. For this I am using the format : USR-<token>

The token is made by this function :

import string
import secrets
def make_token():
    set = string.ascii_letters+string.digits
    while True:
        token = ''.join(secrets.choice(set) for i in range(6))
        if(any(c.islower() for c in token) and
           any(c.isupper() for c in token) and
           sum(c.isdigit() for c in token)>=3 ):
           break
    return token

This function will be called in this database model :

class User(db.Model):
    usrid = db.Column(db.String(10), primary_key=True,
                        default="USR-{}".format(make_token()))
    usrnm = db.Column(db.String(20), unique=True, nullable = False)

I want the token to be new every time. But right now If I commit two User objects it gives me a Constraint Failed : Unique error. Also, I’m using SQLite for testing, if that makes any difference. The model is bigger than this but for the question I think only these parts are relevant.

Advertisement

Answer

I think you need to pass the make_token function AS the default argument, instead of its return value.

So you could try having your make_token function prepend “USR-” to the string:

    # ...
    return "USR-" + token

And then pass that function as the default argument:

    usrid = db.Column(db.String(10), primary_key=True,
                    default=make_token)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement