how to connect python to cassandra that run with docker

  cassandra, docker, docker-toolbox, python

I want get online data and save to cassandra keyspace. I read this guide, https://phoenixnap.com/kb/install-cassandra-on-windows, to run cassandra. It seems easy, but I get error that related to jdk. So, I tried different way. I tried with docker-toolbox (windows 8.1). I run cassndra by these steps in docker-toolbox shell:

$ docker run --name some-cassandra2 --network some-network -d cassandra:latest

$ docker run -it --network some-network --rm cassandra cqlsh some-cassandra2

enter image description here

cqlsh>create keyspace CityInfo with replication = {'class' : 'SimpleStrategy', 'replication_factor':2};

cqlsh>use CityInfo;

cqlsh> CREATE TABLE cities (id int,name text,country text,PRIMARY KEY(id));

cqlsh> CREATE TABLE users (username text,name text,age int,PRIMARY KEY(username));

Now, I want get online data and save to cities and users table with python code. I get online data. I try to connect with this code:

from cassandra.cluster import Cluster
cluster = Cluster(['172.18.0.2'],port=9042)
session = cluster.connect('cityinfo',wait_for_all_pools=False)
session.execute('USE cityinfo')
rows = session.execute('SELECT * FROM users')
for row in rows:
        print(row.age,row.name,row.username)

But I see error:

File "cassandracluster.py", line 3533, in cassandra.cluster.ControlConnection._reconnect_internal

NoHostAvailable: ('Unable to connect to any servers', {'172.18.0.2:9042': OSError(None, "Tried connecting to [('172.18.0.2', 9042)]. Last error: timed out")}) 

I tried several way. For example, I tried with other ip sush as 127.0.0.1:9042, or I added -p7000:7000 when runing cassandra to connect container port to device port. but I can’t.
Please guide me. What is the problem?

Source: Docker Questions

LEAVE A COMMENT