Search code examples
sqlalchemysqlalchemy-utils

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?


Solution

  • 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))