Created
July 19, 2018 12:13
-
-
Save j4mie/2b230f55065df9e2844bb2c6882de5cc to your computer and use it in GitHub Desktop.
Context manager / decorator for stopping the Django ORM from making queries in a given block of code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
from django.db import connections | |
class QueriesDisabledError(Exception): | |
pass | |
def fake(*args, **kwargs): | |
raise QueriesDisabledError() | |
def apply_monkeypatch(): | |
for connection in connections.all(): | |
connection._real_create_cursor = connection.create_cursor | |
connection.create_cursor = fake | |
def remove_monkeypatch(): | |
for connection in connections.all(): | |
connection.create_cursor = connection._real_create_cursor | |
del connection._real_create_cursor | |
@contextmanager | |
def queries_disabled(): | |
apply_monkeypatch() | |
try: | |
yield | |
finally: | |
remove_monkeypatch() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment