python
24 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
import uuid
import logging
class RequestIDMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Generate unique request ID
request_id = str(uuid.uuid4())
request.id = request_id
# Add to logging context
with logging.LoggerAdapter(
logging.getLogger(__name__),
{'request_id': request_id}
):
response = self.get_response(request)
# Include in response headers for client tracking
response['X-Request-ID'] = request_id
return response
1 file · python
Explain with highlit
Adding unique request IDs helps trace logs across distributed systems. I generate a UUID for each request and attach it to both the request object and response headers. I also add it to the logging context so all log entries for that request include the ID. This makes debugging much easier—I can grep logs for a specific request ID to see its full lifecycle. For microservices, I propagate the request ID to downstream services. This simple middleware provides huge value for production debugging and monitoring.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
rust
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
rust
observability
tracing
by Marcus Chen
1 tab
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem
class DashboardView(TemplateView):
Django aggregation with annotate for statistics
django
python
database
by Priya Sharma
1 tab
Share this code
Here's the card — post it anywhere.