You're browsing snippets anonymously. Log in or create an account to save and manage your own snippets.
Public Snippets
Showing
13 snippets
Django Query Stats per request
# stats.py
import time
from django.db import connection
from loguru import logger
class StatsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
...
By
xtream1101
•
•
Updated
2025-05-11 00:04
Reset default python log handlers
import logging
formatter = logging.Formatter('FOO: %(message)s')
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# This is the key line that removes the double logging
...
By
xtream1101
•
•
Updated
2025-03-04 18:33
Check if a server has strictsni enabled
curl -v -k https://1.2.3.4
By
xtream1101
•
•
Updated
2025-02-28 14:13
Firefox hide tab bar
/* Source file https://github.com/MrOtherGuy/firefox-csshacks/tree/master/chrome/hide_tabs_toolbar_v2.css made available under Mozilla Public License v. 2.0
See the above repository for updates as we...
By
xtream1101
•
•
Updated
2025-02-27 21:45
Get domain cert details in cli
DOMAIN=yourdomain.tld
echo | openssl s_client -showcerts -servername $DOMAIN -connect $DOMAIN:443 2>/dev/null | openssl x509 -inform pem -noout -text
By
xtream1101
•
•
Updated
2025-02-12 19:48
List mounted drives
df -h --output=target,size,used,avail,pcent,source | grep -e Mounted -e $1 | awk 'NR<2{print $0;next}{print $0| "sort"}'
By
xtream1101
•
•
Updated
2025-02-08 22:44
Django graphene mutation input validation
import graphene
class ScratchpadMutation(graphene.relay.ClientIDMutation):
class Input:
created_by = graphene.String(required=True)
foobar = graphene.String()
test = g...
By
xtream1101
•
•
Updated
2025-02-06 14:13
Try, try again - Multiple try/except blocks in a flat format
data = {'some_key': 'key value'}
key_data = None
for _ in range(1):
try:
key_data = data['someKey']
except Exception: pass
else: break # It worked
try:
key_d...
By
xtream1101
•
•
Updated
2025-02-06 13:43
Multi key sort on a list of dicts
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'London'},
{'name': 'Charlie', 'age': 20, 'city': 'New York'}
]
# Sort by 'city' first,...
By
xtream1101
•
•
Updated
2025-02-06 13:27
Convert image to dxf file
inkscape --export-type=dxf my-image.svg
By
xtream1101
•
•
Updated
2025-02-06 05:18
Clean up empty dirs
# List/print empty dirs (does not delete)
find /mnt/my-data/ -type d -empty -print
# Delete empty dirs
find /mnt/my-data/ -type d -empty -delete
By
xtream1101
•
•
Updated
2025-02-06 05:15
Bash command test
# Access individual arguments
echo "The first argument is: $1"
echo "The second argument is: $2"
# Access all arguments
echo "All arguments: $@"
# Access the number of arguments
echo "Number...
By
xtream1101
•
•
Updated
2025-02-06 05:13
Showing
13 snippets
Snippet
# stats.py
import time
from django.db import connection
from loguru import logger
class StatsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
"""Capture stats about each request
"""
start_time = time.time()
# Needed in upper environments to get the SQL queries stats
# Otherwise only works when DEBUG="true"
connection.force_debug_cursor = True
queries_before = len(connection.queries)
response = self.get_response(request)
queries_after = len(connection.queries)
duration = time.time() - start_time
num_queries = queries_after - queries_before
try:
total_query_time = sum(float(query["time"]) for query in connection.queries)
logger.info(
f"Time taken: {duration * 1_000:.2f} ms, "
f"SQL queries executed: {num_queries}, "
f"Total query time: {total_query_time * 1_000:.2f} ms",
num_queries=num_queries,
duration=duration,
total_query_time_ms=int(total_query_time * 1_000),
request_body=request.body.decode("utf-8"),
request_method=request.method,
request_path=request.path,
)
# Add some stats to the header so that we can see them in the clients
response["X-Response-Time-ms"] = int(duration * 1_000)
response["X-Total-Queries-Time-ms"] = int(total_query_time * 1_000)
response["X-Total-Queries"] = num_queries
except Exception:
# Never expect this to have an exception
# but better to catch and log, rather then breaking the response
logger.exception("Error logging request stats")
return response
Description
Be sure to add it to your settings.py
middleware
MIDDLEWARE = [
# ...
"my_app.stats.StatsMiddleware",
]
By
xtream1101
•
•
Updated
2025-05-11 00:04