|
| 1 | +title: django.db.backends utils Example Code |
| 2 | +category: page |
| 3 | +slug: django-db-backends-utils-examples |
| 4 | +sortorder: 500011170 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.db.backends utils |
| 7 | +meta: Python example code for the utils callable from the django.db.backends module of the Django project. |
| 8 | + |
| 9 | + |
| 10 | +utils is a callable within the django.db.backends module of the Django project. |
| 11 | + |
| 12 | + |
| 13 | +## Example 1 from django-extensions |
| 14 | +[django-extensions](https://github.com/django-extensions/django-extensions) |
| 15 | +([project documentation](https://django-extensions.readthedocs.io/en/latest/) |
| 16 | +and [PyPI page](https://pypi.org/project/django-extensions/)) |
| 17 | +is a [Django](/django.html) project that adds a bunch of additional |
| 18 | +useful commands to the `manage.py` interface. This |
| 19 | +[GoDjango video](https://www.youtube.com/watch?v=1F6G3ONhr4k) provides a |
| 20 | +quick overview of what you get when you install it into your Python |
| 21 | +environment. |
| 22 | + |
| 23 | +The django-extensions project is open sourced under the |
| 24 | +[MIT license](https://github.com/django-extensions/django-extensions/blob/master/LICENSE). |
| 25 | + |
| 26 | +[**django-extensions / django_extensions / management / debug_cursor.py**](https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/debug_cursor.py) |
| 27 | + |
| 28 | +```python |
| 29 | +# debug_cursor.py |
| 30 | +import six |
| 31 | +import time |
| 32 | +import traceback |
| 33 | +from contextlib import contextmanager |
| 34 | + |
| 35 | +import django |
| 36 | +from django.conf import settings |
| 37 | +from django.core.exceptions import ImproperlyConfigured |
| 38 | +~~from django.db.backends import utils |
| 39 | + |
| 40 | + |
| 41 | +@contextmanager |
| 42 | +def monkey_patch_cursordebugwrapper(print_sql=None, print_sql_location=False, truncate=None, logger=six.print_, confprefix="DJANGO_EXTENSIONS"): |
| 43 | + if not print_sql: |
| 44 | + yield |
| 45 | + else: |
| 46 | + truncate = getattr(settings, '%s_PRINT_SQL_TRUNCATE' % confprefix, 1000) |
| 47 | + |
| 48 | + sqlparse = None |
| 49 | + if getattr(settings, '%s_SQLPARSE_ENABLED' % confprefix, True): |
| 50 | + try: |
| 51 | + import sqlparse |
| 52 | + |
| 53 | + sqlparse_format_kwargs_defaults = dict( |
| 54 | + reindent_aligned=True, |
| 55 | + truncate_strings=500, |
| 56 | + ) |
| 57 | + sqlparse_format_kwargs = getattr(settings, '%s_SQLPARSE_FORMAT_KWARGS' % confprefix, sqlparse_format_kwargs_defaults) |
| 58 | + except ImportError: |
| 59 | + sqlparse = None |
| 60 | + |
| 61 | + pygments = None |
| 62 | + if getattr(settings, '%s_PYGMENTS_ENABLED' % confprefix, True): |
| 63 | + try: |
| 64 | + import pygments.lexers |
| 65 | + import pygments.formatters |
| 66 | + |
| 67 | + pygments_formatter = getattr(settings, '%s_PYGMENTS_FORMATTER' % confprefix, pygments.formatters.TerminalFormatter) |
| 68 | + pygments_formatter_kwargs = getattr(settings, '%s_PYGMENTS_FORMATTER_KWARGS' % confprefix, {}) |
| 69 | + except ImportError: |
| 70 | + pass |
| 71 | + |
| 72 | + class PrintQueryWrapperMixin: |
| 73 | + def execute(self, sql, params=()): |
| 74 | + starttime = time.time() |
| 75 | + try: |
| 76 | +~~ return utils.CursorWrapper.execute(self, sql, params) |
| 77 | + finally: |
| 78 | + execution_time = time.time() - starttime |
| 79 | + raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params) |
| 80 | + if truncate: |
| 81 | + raw_sql = raw_sql[:truncate] |
| 82 | + |
| 83 | + if sqlparse: |
| 84 | + raw_sql = sqlparse.format(raw_sql, **sqlparse_format_kwargs) |
| 85 | + |
| 86 | + if pygments: |
| 87 | + raw_sql = pygments.highlight( |
| 88 | + raw_sql, |
| 89 | + pygments.lexers.get_lexer_by_name("sql"), |
| 90 | + pygments_formatter(**pygments_formatter_kwargs), |
| 91 | + ) |
| 92 | + |
| 93 | + logger(raw_sql) |
| 94 | + logger("Execution time: %.6fs [Database: %s]" % (execution_time, self.db.alias)) |
| 95 | + if print_sql_location: |
| 96 | + logger("Location of SQL Call:") |
| 97 | + logger(''.join(traceback.format_stack())) |
| 98 | + |
| 99 | +~~ _CursorDebugWrapper = utils.CursorDebugWrapper |
| 100 | + |
| 101 | + class PrintCursorQueryWrapper(PrintQueryWrapperMixin, _CursorDebugWrapper): |
| 102 | + pass |
| 103 | + |
| 104 | + try: |
| 105 | + from django.db import connections |
| 106 | + _force_debug_cursor = {} |
| 107 | + for connection_name in connections: |
| 108 | + _force_debug_cursor[connection_name] = connections[connection_name].force_debug_cursor |
| 109 | + except Exception: |
| 110 | + connections = None |
| 111 | + |
| 112 | +~~ utils.CursorDebugWrapper = PrintCursorQueryWrapper |
| 113 | + |
| 114 | + postgresql_base = None |
| 115 | + if django.VERSION >= (3, 0): |
| 116 | + try: |
| 117 | + from django.db.backends.postgresql import base as postgresql_base |
| 118 | + _PostgreSQLCursorDebugWrapper = postgresql_base.CursorDebugWrapper |
| 119 | + |
| 120 | + class PostgreSQLPrintCursorDebugWrapper(PrintQueryWrapperMixin, _PostgreSQLCursorDebugWrapper): |
| 121 | + pass |
| 122 | + except (ImproperlyConfigured, TypeError): |
| 123 | + postgresql_base = None |
| 124 | + |
| 125 | + if postgresql_base: |
| 126 | + postgresql_base.CursorDebugWrapper = PostgreSQLPrintCursorDebugWrapper |
| 127 | + |
| 128 | + if connections: |
| 129 | + for connection_name in connections: |
| 130 | + connections[connection_name].force_debug_cursor = True |
| 131 | + |
| 132 | + yield |
| 133 | + |
| 134 | +~~ utils.CursorDebugWrapper = _CursorDebugWrapper |
| 135 | + |
| 136 | + if postgresql_base: |
| 137 | + postgresql_base.CursorDebugWrapper = _PostgreSQLCursorDebugWrapper |
| 138 | + |
| 139 | + if connections: |
| 140 | + for connection_name in connections: |
| 141 | + connections[connection_name].force_debug_cursor = _force_debug_cursor[connection_name] |
| 142 | + |
| 143 | + |
| 144 | + |
| 145 | +## ... source file continues with no further utils examples... |
| 146 | + |
| 147 | +``` |
| 148 | + |
0 commit comments