@@ -858,10 +858,25 @@ def _unblocked_async_only(self, *args, **kwargs):
858
858
elif self ._real_ensure_connection is not None :
859
859
self ._real_ensure_connection (* args , ** kwargs )
860
860
861
- def unblock (self , async_only = False ) -> AbstractContextManager [None ]:
861
+ def _unblocked_sync_only (self , * args , ** kwargs ):
862
+ __tracebackhide__ = True
863
+ if threading .current_thread () != threading .main_thread ():
864
+ raise RuntimeError (
865
+ "Database access is only allowed in the main thread, "
866
+ "modify your test fixtures to be sync or use the transactional_db fixture."
867
+ "See https://pytest-django.readthedocs.io/en/latest/database.html#db-thread-safeguards for more information."
868
+ )
869
+ elif self ._real_ensure_connection is not None :
870
+ self ._real_ensure_connection (* args , ** kwargs )
871
+
872
+ def unblock (self , sync_only = False , async_only = False ) -> AbstractContextManager [None ]:
862
873
"""Enable access to the Django database."""
874
+ if sync_only and async_only :
875
+ raise ValueError ("Cannot use both sync_only and async_only. Choose at most one." )
863
876
self ._save_active_wrapper ()
864
- if async_only :
877
+ if sync_only :
878
+ self ._dj_db_wrapper .ensure_connection = self ._unblocked_sync_only
879
+ elif async_only :
865
880
self ._dj_db_wrapper .ensure_connection = self ._unblocked_async_only
866
881
else :
867
882
self ._dj_db_wrapper .ensure_connection = self ._real_ensure_connection
0 commit comments