Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to connect python to cassandra that run with docker

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 "cassandra\cluster.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?

like image 803
Ali Hosein pour Avatar asked Sep 12 '25 05:09

Ali Hosein pour


1 Answers

I suggest running your Python code from a container running on the same network, thus you can use the container name instead of the IP address directly in Python. I was able to run your code with no problem doing the following.

I created a docker container running Python, also running on some-network.

docker run -it --rm --network some-network python:3.8-slim bash

Proceeded to install cassandra-driver inside the container.

pip install cassandra-driver

Filled some dummy data in the users table and proceeded to open a Python terminal.

from cassandra.cluster import Cluster
cluster = Cluster(['some-cassandra2'], 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)

Notice that the only difference with your code is this line where I use the container name instead of the IP address:

cluster = Cluster(['some-cassandra2'], port=9042)
like image 72
P. Cabaleiro Avatar answered Sep 14 '25 19:09

P. Cabaleiro