【问题标题】:how to connect python to cassandra that run with docker如何将 python 连接到使用 docker 运行的 cassandra
【发布时间】:2021-09-26 07:27:46
【问题描述】:

我想获取在线数据并保存到 cassandra 密钥空间。我阅读了本指南,https://phoenixnap.com/kb/install-cassandra-on-windows,以运行 cassandra。这似乎很容易,但我得到了与 jdk 相关的错误。所以,我尝试了不同的方式。我尝试使用 docker-toolbox(Windows 8.1)。我在 docker-toolbox shell 中通过以下步骤运行 cassndra:

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

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

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));

现在,我想使用 python 代码获取在线数据并保存到城市和用户表中。我得到在线数据。我尝试使用此代码进行连接:

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)

但我看到错误:

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")}) 

我尝试了几种方法。例如,我尝试将其他ip sush 设置为 127.0.0.1:9042,或者我在运行 cassandra 以将容器端口连接到设备端口时添加了 -p7000:7000。但我不能。 请指导我。有什么问题?

【问题讨论】:

  • 尝试使用容器名而不是ip
  • 在python代码中?我试过了。没用。
  • 客户端代码在哪里运行?几乎所有环境中都无法访问容器专用 IP 地址。从另一个容器,它需要在同一个 Docker 网络上,问题中的cqlsh 调用是对的。在 Docker 外部,在 Docker Toolbox 上,您需要 VM 的 IP 地址。
  • 我为它工作了一整天。首先,我想在 docker 上运行 cassandra,在 spyder 中运行 python 代码。但正如你所说,这是不可能的。然后,我阅读了不同的资料并对其进行了测试。其中之一已在此 towardsdatascience.com/… 进行了解释。在这个地址中,python 代码在 docker shell 上运行。如前所述,我用两种方法逐步尝试了它。首先,我将 python 代码作为容器运行。它发布了同样的错误。其次,我直接运行python代码。它无法导入 cassandra-driver。有什么解决办法吗?

标签: python docker cassandra docker-toolbox


【解决方案1】:

我建议从运行在同一网络上的容器中运行您的 Python 代码,因此您可以直接在 Python 中使用容器名称而不是 IP 地址。我能够毫无问题地运行您的代码。

我创建了一个运行 Python 的 docker 容器,也在 some-network 上运行。

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

继续在容器内安装 cassandra-driver。

pip install cassandra-driver

users 表中填充了一些虚拟数据,然后继续打开 Python 终端。

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)

请注意,与您的代码的唯一区别是这一行我使用容器名称而不是 IP 地址:

cluster = Cluster(['some-cassandra2'], port=9042)

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2018-05-20
    • 2023-02-10
    • 2018-11-21
    • 2019-08-13
    • 2023-03-10
    • 2016-04-03
    • 2016-04-11
    • 2021-01-02
    相关资源
    最近更新 更多