Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Django middleware metric collector pattern example
import datetime
import logging
from django.conf import settings
from kafka import KafkaProducer
# from pykafka import KafkaClient
class MetricCollectorMiddleware:
def __init__(self, get_response):
self._kafka_client = self._init_mq_client()
self.get_response = get_response
self._debug_log("MetricCollectorMiddleware init")
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
self._debug_log("MetricCollectorMiddleware call")
before =
response = self.get_response(request)
after =
# Code to be executed for each request/response after
# the view is called.
_message_content = 'test message from Kafka-Python at {}'.format(
"%B the %d of %Y is %A at %I:%M %p"))
self._mq_client_send_message('testtopic', _message_content)
"process request time {}".format((after - before).total_seconds()))
return response
def _debug_log(message):
if settings.DEBUG:
logging.log(level=logging.DEBUG, msg=message)
def _init_mq_client():
if settings.KAFKA.get("ENABLE"):
return KafkaProducer(
# return KafkaClient(hosts="localhost:9093")
return None
def _mq_client_send_message(self, topic, message='', async_way=False):
if settings.KAFKA.get("ENABLE"):
self._kafka_client.send(topic, message.encode('utf-8'))
# topic = self._kafka_client.topics[topic]
# if topic:
# with topic.get_sync_producer() as producer:
# producer.produce(message.encode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment