def open_db(self, keyspace_init=None, reuse_keyspace=True):
        cluster = Cluster()  # Cluster([self.host], port=self.port)
        cluster.connect_timeout = 20

        try:
            self.session = cluster.connect()
        except cassandra.cluster.NoHostAvailable:
            print "Ensure an instantiation of Cassandra is running."
            sys.exit()

        if reuse_keyspace:
            try:
                self.session.execute("USE {}".format(self.keyspace))
            except (cassandra.InvalidRequest, ConfigurationException):
                print "Keyspace: '{}' does not exists, creating the keyspace.".format(self.keyspace)
                self.create_keyspace(keyspace_init)
                time.sleep(0.5)  # Sleep half a second.
                self.session.execute("USE {}".format(self.keyspace))
        else:
            try:
                self.session.execute("DROP KEYSPACE {};".format(self.keyspace), timeout=60)
            except (cassandra.InvalidRequest, ConfigurationException):
                print "Keyspace: '{}' does not exists, creating the keyspace.".format(self.keyspace)

            self.create_keyspace(keyspace_init)
            time.sleep(0.5)  # Sleep half a second.
            self.session.execute("USE {}".format(self.keyspace))
        return self.session
Exemple #2
0
from cassandra.policies import ConstantReconnectionPolicy, DCAwareRoundRobinPolicy
from json import dumps
from kafka import KafkaProducer
import time
import io
import socket

# $ sudo pip install python-dateutil

cluster = Cluster(
    contact_points=['192.168.1.233', '192.168.1.77', '192.168.1.27'],
    idle_heartbeat_interval=5,
    load_balancing_policy=DCAwareRoundRobinPolicy(),
    reconnection_policy=ConstantReconnectionPolicy(delay=5, max_attempts=50),
    idle_heartbeat_timeout=5)
cluster.connect_timeout = 30
session = cluster.connect('temperature')

sleep_time = 1  #in seconds

# pip install kafka-python
producer = KafkaProducer(bootstrap_servers=['192.168.1.167:9092'],
                         value_serializer=lambda x: dumps(x).encode('utf-8'))

# test

# /test

# main endless loop
while True: