Created
September 25, 2023 06:55
-
-
Save jairajsahgal/14521cd3f401b40e6be0b7ee2f23a224 to your computer and use it in GitHub Desktop.
The query_debugger function is a Python decorator used for debugging and profiling database queries in a Django application.
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
def query_debugger(func): | |
@functools.wraps(func) | |
def inner_func(*args, **kwargs): | |
reset_queries() | |
start_queries = len(connection.queries) | |
start = time.perf_counter() | |
result = func(*args, **kwargs) | |
end = time.perf_counter() | |
logger.info(connection.queries[start_queries:]) | |
end_queries = len(connection.queries) | |
logger.info("QUERIES") | |
logger.info(f"Function : {func.__name__}") | |
logger.info(f"Number of Queries : {end_queries - start_queries}") | |
logger.info(f"Finished in : {(end - start):.2f}s") | |
return result | |
return inner_func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Purpose: This Python decorator is designed to assist in debugging and profiling database queries when working with a Django web application.
How it works: When applied to a function or method, it does the following:
Uses functools.wraps to preserve the original function's metadata.
Resets the list of recorded database queries using reset_queries().
Records the number of database queries executed before the decorated function is called.
Measures the time taken for the decorated function to execute.
Logs the database queries executed during the function's execution.
Logs information about the function's name, the number of new queries executed, and the time taken for execution.
Returns the result of the decorated function.
Usage: Apply this decorator to Django views or functions where you want to monitor and log database query activity.
Example Usage:
python
Output: When this decorator is applied to a function, it will log information about the queries executed within that function, helping developers identify and optimize database query performance.
Note: Ensure you have the necessary imports for functools, time, logger, reset_queries(), and connection.queries for this decorator to work correctly within a Django environment.