I was looking at ways to delay the database connection initiated from pewee. Since the code runs in lambda, and is guaranteed to run in parallel, and many times, lazy loading is the only way to go , unless I'm missing something. Found an article which sheds some insight into it, Lazy Loading with Peewee Proxy; The gist of the article is to initialize the proxy if obj
attribute is None
.
What I'm currently doing is as shown below,
db.py
my_runtime_db = MySQLDatabase('myDatabaseName',
**{'host': 'localhost',
'user': 'root'
'password': "superS3cr3t",
'port': 3306,
})
global_database_object = DatabaseProxy()
global_database_object.initialize(my_runtime_db)
basemodel.py
class BaseModel(Model):
"""Basemodel from which all other peewee models are derived.
"""
class Meta:
database = global_database_object
testmodel.py
class TestModel(BaseModel):
class Meta:
table_name = 'testmodel'
primary_key = CompositeKey('id', 'mid')
What is the advantage of creating a subclass of Proxy
over DatabaseProxy
?
Is there any advantage or disadvantage in making a proxy connection this way when running in AWS lambda containers, which is massively parallelized?
Ref:
https://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=Proxy#Proxy https://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=Proxy#DatabaseProxy
CodePudding user response:
DatabaseProxy
, as can easily be seen from the code, implements proper handling for module-scope usage of atomic()
as well as a handful of other context managers/decorators. So you can write:
db = DatabaseProxy()
@db.atomic()
def run_in_tx():
...
The DatabaseProxy
ensures that you can do this, otherwise you would get a "can't use uninitialized proxy".