My Stack is uwsgi with gevents. I am trying to wrap my api end points with a decorator to push all request data (url, method, body and response) to a kafka topic, But its not working. My theory is because I am using gevents, and I am trying to run these in async mode, the async thread which actually pushes to kafka, is not able to run with gevents. And If I try to make the method sync, Then also it does not work, it dies in the produce worker, i.e. after produce the call never returns. Although both the methods work good on python shell and if I run uwsgi on threads.
Follows the sample code: 1. with kafka-python (async)
try:
kafka_producer = KafkaProducer(bootstrap_servers=KAFKAHOST.split(','))
except NoBrokersAvailable:
logger.info(u'Kafka Host not available: {}'.format(KAFKAHOST))
kafka_producer = None
def send_message_to_kafka(topic, key, message):
"""
:param topic: topic name
:param key: key to decide partition
:param message: json serializable object to send
:return:
"""
if not kafka_producer:
logger.info(u'Kafka Host not available: {}'.format(KAFKAHOST))
return
data = json.dumps(message)
try:
start = time.time()
kafka_producer.send(topic, key=str(key), value=data)
logger.info(u'Time take to push to Kafka: {}'.format(time.time() - start))
except KafkaTimeoutError as e:
logger.info(u'Message not sent: {}'.format(KAFKAHOST))
logger.info(e)
pass
except Exception as e:
logger.info(u'Message not sent: {}'.format(KAFKAHOST))
logger.exception(e)
pass
with py-kafka (sync):
try: client = KafkaClient(hosts=KAFKAHOST) except Exception as e: logger.info(u'Kafka Host Not Found: {}'.format(KAFKAHOST)) client = None def send_message_to_kafka(topic, key, message): """ :param topic: topic name :param key: key to decide partition :param message: json serializable object to send :return: """ if not client: logger.info(u'Kafka Host is None') return data = json.dumps(message) try: start = time.time() topic = client.topics[topic] with topic.get_sync_producer() as producer: producer.produce(data, partition_key='{}'.format(key)) logger.info(u'Time take to push to Kafka: {}'.format(time.time() - start)) except Exception as e: logger.exception(e) pass