Skip to content

Commit

Permalink
Add documentation note about thread-safe database metadata impl.
Browse files Browse the repository at this point in the history
  • Loading branch information
coleifer committed Feb 10, 2021
1 parent 3f66b5d commit ea1ae2c
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions docs/peewee/database.rst
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,37 @@ for binding a given model class:
The :ref:`testing` section of this document also contains some examples of
using the ``bind()`` methods.

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:

.. code-block:: python
import threading
from peewee import Metadata
class ThreadSafeDatabaseMetadata(Metadata):
def __init__(self, *args, **kwargs):
# database attribute is stored in a thread-local.
self._local = threading.local()
super(ThreadSafeDatabaseMetadata, self).__init__(*args, **kwargs)
def _get_db(self):
return getattr(self._local, 'database', self._database)
def _set_db(self, db):
self._local.database = self._database = db
database = property(_get_db, _set_db)
class BaseModel(Model):
class Meta:
# Instruct peewee to use our thread-safe metadata implementation.
model_metadata_class = ThreadSafeDatabaseMetadata
Connection Management
---------------------

Expand Down

0 comments on commit ea1ae2c

Please sign in to comment.