instrumentation.txt 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. ========================
  2. Database instrumentation
  3. ========================
  4. .. versionadded:: 2.0
  5. To help you understand and control the queries issued by your code, Django
  6. provides a hook for installing wrapper functions around the execution of
  7. database queries. For example, wrappers can count queries, measure query
  8. duration, log queries, or even prevent query execution (e.g. to make sure that
  9. no queries are issued while rendering a template with prefetched data).
  10. The wrappers are modeled after :doc:`middleware </topics/http/middleware>` --
  11. they are callables which take another callable as one of their arguments. They
  12. call that callable to invoke the (possibly wrapped) database query, and they
  13. can do what they want around that call. They are, however, created and
  14. installed by user code, and so don't need a separate factory like middleware do.
  15. Installing a wrapper is done in a context manager -- so the wrappers are
  16. temporary and specific to some flow in your code.
  17. As mentioned above, an example of a wrapper is a query execution blocker. It
  18. could look like this::
  19. def blocker(*args):
  20. raise Exception('No database access allowed here.')
  21. And it would be used in a view to block queries from the template like so::
  22. from django.db import connection
  23. from django.shortcuts import render
  24. def my_view(request):
  25. context = {...} # Code to generate context with all data.
  26. template_name = ...
  27. with connection.execute_wrapper(blocker):
  28. return render(request, template_name, context)
  29. The parameters sent to the wrappers are:
  30. * ``execute`` -- a callable, which should be invoked with the rest of the
  31. parameters in order to execute the query.
  32. * ``sql`` -- a ``str``, the SQL query to be sent to the database.
  33. * ``params`` -- a list/tuple of parameter values for the SQL command, or a
  34. list/tuple of lists/tuples if the wrapped call is ``executemany()``.
  35. * ``many`` -- a ``bool`` indicating whether the ultimately invoked call is
  36. ``execute()`` or ``executemany()`` (and whether ``params`` is expected to be
  37. a sequence of values, or a sequence of sequences of values).
  38. * ``context`` -- a dictionary with further data about the context of
  39. invocation. This includes the connection and cursor.
  40. Using the parameters, a slightly more complex version of the blocker could
  41. include the connection name in the error message::
  42. def blocker(execute, sql, params, many, context):
  43. alias = context['connection'].alias
  44. raise Exception("Access to database '{}' blocked here".format(alias))
  45. For a more complete example, a query logger could look like this::
  46. import time
  47. class QueryLogger:
  48. def __init__(self):
  49. self.queries = []
  50. def __call__(self, execute, sql, params, many, context):
  51. current_query = {'sql': sql, 'params': params, 'many': many}
  52. start = time.time()
  53. try:
  54. result = execute(sql, params, many, context)
  55. except Exception as e:
  56. current_query['status'] = 'error'
  57. current_query['exception'] = e
  58. raise
  59. else:
  60. current_query['status'] = 'ok'
  61. return result
  62. finally:
  63. duration = time.time() - start
  64. current_query['duration'] = duration
  65. self.queries.append(current_query)
  66. To use this, you would create a logger object and install it as a wrapper::
  67. from django.db import connection
  68. ql = QueryLogger()
  69. with connection.execute_wrapper(ql):
  70. do_queries()
  71. # Now we can print the log.
  72. print(ql.queries)
  73. .. currentmodule:: django.db.backends.base.DatabaseWrapper
  74. ``connection.execute_wrapper()``
  75. --------------------------------
  76. .. method:: execute_wrapper(wrapper)
  77. Returns a context manager which, when entered, installs a wrapper around
  78. database query executions, and when exited, removes the wrapper. The wrapper is
  79. installed on the thread-local connection object.
  80. ``wrapper`` is a callable taking five arguments. It is called for every query
  81. execution in the scope of the context manager, with arguments ``execute``,
  82. ``sql``, ``params``, ``many``, and ``context`` as described above. It's
  83. expected to call ``execute(sql, params, many, context)`` and return the return
  84. value of that call.