Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a key for SQLAlchemy's `EncryptedType` at runtime

The SQLAlchemy-Utils documentation for the EncryptedType column type has an example that looks something like this:

secret_key = 'secretkey1234'
# setup
engine = create_engine('sqlite:///:memory:')
connection = engine.connect()
Base = declarative_base()


class User(Base):
    __tablename__ = "user"
    id = sa.Column(sa.Integer, primary_key=True)
    username = sa.Column(EncryptedType(sa.Unicode,
                                       secret_key,
                                       AesEngine,
                                       'pkcs5'))

But what if I don't know what the secret key is before I define the User class? For example, what if I want to prompt the user to enter the secret key?

like image 876
John Wiseman Avatar asked Jul 27 '26 06:07

John Wiseman


1 Answers

This is the last example in the docs that you linked to:

The key parameter accepts a callable to allow for the key to change per-row instead of being fixed for the whole table.

def get_key():
    return 'dynamic-key'

class User(Base):
    __tablename__ = 'user'
    id = sa.Column(sa.Integer, primary_key=True)
    username = sa.Column(EncryptedType(
        sa.Unicode, get_key))
like image 117
SuperShoot Avatar answered Jul 29 '26 21:07

SuperShoot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!