2
0

instrumentation.txt 4.2 KB

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