Thread-Safety and Multiple Databases

If you plan to change the database at run-time in a multi-threaded application, storing the model’s database in a thread-local will prevent race-conditions. This can be accomplished with a custom model Metadata class:

  1. import threading
  2. from peewee import Metadata
  3. class ThreadSafeDatabaseMetadata(Metadata):
  4. def __init__(self, *args, **kwargs):
  5. # database attribute is stored in a thread-local.
  6. self._local = threading.local()
  7. super(ThreadSafeDatabaseMetadata, self).__init__(*args, **kwargs)
  8. def _get_db(self):
  9. return getattr(self._local, 'database', self._database)
  10. def _set_db(self, db):
  11. self._local.database = self._database = db
  12. database = property(_get_db, _set_db)
  13. class BaseModel(Model):
  14. class Meta:
  15. # Instruct peewee to use our thread-safe metadata implementation.
  16. model_metadata_class = ThreadSafeDatabaseMetadata