Search code examples
pythonpeewee

Python: How to dynamically set inner class class variable


I am working with peewee and SQLite on a project. I have two files:

file1.py

if __name__ == '__main__':
    db = Thing()

file2.py

DB_FILENAME = 'db_name.db'
DB_FILE_PATH = f'/tmp/{DB_FILENAME}'
db = SqliteDatabase(DB_FILE_PATH)

class Thing(Model):
    field1 = CharField(primary_key=True)
    field2 = CharField()

    class Meta:
        database = db

The Thing class needs to be able to write into several different databases so I need a clean way of making DB_FILENAME configurable so that the inner class database field will be initialized to the appropriate name.

The inner Meta class appears to be required and this setup is what is referenced in the documentation (the db declared globally). Additional Note: This code is being run in AWS Lambda.

EDIT: Working solution in fact did not work.


Solution

  • Write a function that creates the class, and call it with the environment variable as an argument.

    # file2.py
    
    def make_model(db_file_name):
        class Thing(Model):
            field1 = CharField(primary_key=True)
            field2 = CharField()
    
            class Meta:
                database = SqliteDatabase(f'/tmp/{db_file_name}')
    
        return Thing
    
    
    # script
    
    from file2 import make_model
    
    if __name__ == '__main__':
        db = make_model(f'db_name_{os.getenv("SUFFIX")}.db')