无法用Python连接Cassandra

1 投票
2 回答
2321 浏览
提问于 2025-04-18 15:28

我正在尝试从Python连接到Cassandra数据库,我通过命令pip install pycassa安装了cassandra。但是,当我尝试连接到cassandra时,出现了以下错误:

from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160

我使用的是Python 2.7。请问这是什么问题?如果有人能帮忙,我将非常感激。

2 个回答

0

用Python连接Cassandra的通用方法。

from cassandra.cluster import Cluster  
cluster = Cluster()    #for connecting on localhost  
cluster = Cluster(['192.168.0.1', '192.168.0.2']) #*for connecting on clusters (comment this line, if you are connecting with localhost)*  
session = cluster.connect('testing')

你也可以通过模型类来用Python连接。

from cassandra.cqlengine import columns  
from cassandra.cqlengine.models import  Model  
from cassandra.cqlengine.management import sync_table  
from cassandra.cqlengine import connection  
import uuid  
from datetime import datetime  

connection.setup(['127.0.0.1'], "testing")  #testing is the keyspace

想了解模型类的具体实现,可以查看这里: https://github.com/vishal-kr-yadav/NoSQL_Databases

0

你可以试着指定一下主机:

pool = ConnectionPool('Keyspace1', ['server_node_here:9160'])

撰写回答