本文整理汇总了Python中cassandra.cluster.Cluster.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Cluster.connect方法的具体用法?Python Cluster.connect怎么用?Python Cluster.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cassandra.cluster.Cluster
的用法示例。
在下文中一共展示了Cluster.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getEntrysInfo
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def getEntrysInfo(keyspaceid,columnfamilyid,entryname):
cluster = Cluster()
session = cluster.connect('system')
rows = session.execute('select * from schema_keyspaces')
info = []
if int(keyspaceid) < (len(rows) + 1) and int(keyspaceid) > 0:
info = {}
info['name'] = rows[int(keyspaceid) -1][0]
keyspacename = rows[int(keyspaceid) -1][0]
rows = session.execute("SELECT * FROM schema_columnfamilies where keyspace_name='" + info['name'] + "'")
columnfamilyname = rows[int(columnfamilyid)-1][1]
primarykey = rows[int(columnfamilyid)-1]
session = cluster.connect(rows[int(keyspaceid)-1][0])
primarykey = primarykey[17][2:]
primarykey = primarykey[:-2]
query = "SELECT * FROM " + columnfamilyname + " WHERE " + primarykey + "='" + entryname + "'"
rows = session.execute(query)
info = rows
query = "SELECT * FROM system.schema_columns WHERE keyspace_name='" + keyspacename + "' AND columnfamily_name = '" + columnfamilyname + "'"
rows = session.execute(query)
fields = []
for i in rows:
fields.append(i)
temp = fields[len(rows) - 1]
fields[len(rows) - 1] = fields[0]
fields[0] = temp
temp = fields[1]
fields[1] = fields[2]
fields[2] = temp
return render_template('entryinfo.html',info=info,fields=fields,keyspaceid=keyspaceid,columnfamilyid=columnfamilyid,entryname=entryname)
示例2: getEntrys
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def getEntrys(page,keyspaceid,columnfamilyid):
cluster = Cluster()
session = cluster.connect('system')
rows = session.execute('select * from schema_keyspaces')
info = []
if int(keyspaceid) < (len(rows) + 1) and int(keyspaceid) > 0:
info = {}
info['name'] = rows[int(keyspaceid) -1][0]
keyspacename = rows[int(keyspaceid) -1][0]
rows = session.execute("SELECT * FROM schema_columnfamilies where keyspace_name='" + info['name'] + "'")
columnfamilyname = rows[int(columnfamilyid)-1][1]
session = cluster.connect(rows[int(keyspaceid)-1][0])
rows = session.execute("SELECT * FROM " + columnfamilyname)
info = rows
rows = session.execute("SELECT * FROM system.schema_columns WHERE keyspace_name = '" + keyspacename + "' AND columnfamily_name = '" + columnfamilyname + "'")
fields = []
for i in rows:
fields.append(i)
temp = fields[len(rows) - 1]
fields[len(rows) - 1] = fields[0]
fields[0] = temp
temp = fields[1]
fields[1] = fields[2]
fields[2] = temp
else:
return render_template('error.html',error="Not a valid keyspaceid")
pages = info[(page-1)*PER_PAGE:PER_PAGE*page]
if not pages and page != 1:
abort(404)
pagination = Pagination(page, PER_PAGE, len(info))
return render_template('listentrys.html',pagination=pagination,keyspaceid=keyspaceid,columnfamilyid=columnfamilyid,pages=pages,fields=fields,section = 'getEntrys')
示例3: test_pool_management
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_pool_management(self):
# Ensure that in_flight and request_ids quiesce after cluster operations
cluster = Cluster(protocol_version=PROTOCOL_VERSION, idle_heartbeat_interval=0) # no idle heartbeat here, pool management is tested in test_idle_heartbeat
session = cluster.connect()
session2 = cluster.connect()
# prepare
p = session.prepare("SELECT * FROM system.local WHERE key=?")
self.assertTrue(session.execute(p, ('local',)))
# simple
self.assertTrue(session.execute("SELECT * FROM system.local WHERE key='local'"))
# set keyspace
session.set_keyspace('system')
session.set_keyspace('system_traces')
# use keyspace
session.execute('USE system')
session.execute('USE system_traces')
# refresh schema
cluster.refresh_schema_metadata()
cluster.refresh_schema_metadata(max_schema_agreement_wait=0)
# submit schema refresh
future = cluster.submit_schema_refresh()
future.result()
assert_quiescent_pool_state(self, cluster)
cluster.shutdown()
示例4: try_connecting
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def try_connecting(username='', password=''):
"""
Wait until can connect to cluster.
When cluster starts up there is some time while it is not possible to connect to it even though
Cassandra is listening on port 7000. Here we wait until we can actually issue successful Cluster.connect()
method.
:param username: optional user name for connection
:param password: optional password for connection
:return: True if can successfully connect to cluster within 2 minutes, False otherwise
"""
if username and password:
ap = AuthenticationTests.get_authentication_provider(username, password)
else:
ap = None
maxwait = 120 # in seconds
sleeptime = 1
wait_time = 0
while wait_time < maxwait:
try:
cluster = Cluster(protocol_version=tests.integration.PROTOCOL_VERSION, auth_provider=ap)
cluster.connect()
log.debug("Can connect after %d seconds" % wait_time)
return True
except Exception:
wait_time += sleeptime
time.sleep(sleeptime)
return False
示例5: connect_cassandra
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def connect_cassandra():
error = False
cluster = Cluster([config.get('cassandra', 'db_host')], port=config.get('cassandra', 'db_port'),
protocol_version=3, idle_heartbeat_interval=120)
try:
LOG.info("Connecting to Cassandra..")
return cluster.connect(config.get('cassandra', 'keyspace'))
except NoHostAvailable:
error = True
LOG.info("ERROR: Check Cassandra connection settings in conf")
except InvalidRequest:
LOG.info("ERROR: Could not find existing Cassandra keyspace. will create new one")
try:
db_connection = cluster.connect()
CREATE_KEYSPACE = """
CREATE KEYSPACE %s WITH replication = {'class': '%s', 'replication_factor': %s }
""" % (config.get('cassandra', 'keyspace'),
config.get('cassandra', 'replication_strategy'),
config.get('cassandra', 'replication_factor'))
db_connection.execute(CREATE_KEYSPACE)
db_connection.set_keyspace(config.get('cassandra', 'keyspace'))
LOG.info("Created and session set to new keyspace: %s" % config.get('cassandra', 'keyspace'))
return db_connection
except SyntaxException:
error = True
LOG.info("ERROR: couldn't create new keyspace. check keyspace settings in conf. Exiting now.")
raise
except:
error = True
LOG.info("ERROR: something wrong with Cassandra connection")
finally:
if error:
LOG.info("Exiting..")
sys.exit(0)
示例6: copy_model
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def copy_model(**kwargs):
conf = Configuration('global').configuration
cluster_source = Cluster(conf['cassandra']['hosts'])
source = cluster_source.connect(conf['cassandra']['keyspace'])
source.row_factory = dict_factory
cluster_dest = Cluster(conf['new_cassandra']['hosts'])
dest = cluster_dest.connect(conf['new_cassandra']['keyspace'])
table = kwargs['model'].lower()
fetch_size = kwargs.get('fetch_size', 100)
query = "SELECT * FROM {0}".format(table)
if 'where' in kwargs and kwargs['where']:
query = "{0} WHERE {1} ALLOW FILTERING".format(query, kwargs['where'])
statement = SimpleStatement(query, fetch_size=fetch_size)
insert_query = "INSERT INTO {0} ({1}) VALUES ({2})"
cpt = 0
insert = None
for row in source.execute(statement):
if cpt == 0:
columns = ['"{}"'.format(x) for x in row.keys()]
binds = ['?' for x in range(0, len(columns))]
insert_str = insert_query.format(table,
','.join(columns),
','.join(binds))
insert = dest.prepare(insert_str)
bound = insert.bind(row.values())
dest.execute(bound)
cpt += 1
print('Copy of {} records from {}'.format(cpt, table))
return cpt
示例7: test_cannot_connect_with_bad_client_auth
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_cannot_connect_with_bad_client_auth(self):
"""
Test to validate that we cannot connect with invalid client auth.
This test will use bad keys/certs to preform client authentication. It will then attempt to connect
to a server that has client authentication enabled.
@since 2.7.0
@expected_result The client will throw an exception on connect
@test_category connection:ssl
"""
# Setup absolute paths to key/cert files
abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS)
abs_driver_keyfile = os.path.abspath(DRIVER_KEYFILE)
abs_driver_certfile = os.path.abspath(DRIVER_CERTFILE_BAD)
cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options={'ca_certs': abs_path_ca_cert_path,
'ssl_version': ssl.PROTOCOL_TLSv1,
'keyfile': abs_driver_keyfile,
'certfile': abs_driver_certfile})
with self.assertRaises(NoHostAvailable) as context:
cluster.connect()
cluster.shutdown()
示例8: test_can_register_udt_before_connecting
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_can_register_udt_before_connecting(self):
"""
Test the registration of UDTs before session creation
"""
c = Cluster(protocol_version=PROTOCOL_VERSION)
s = c.connect()
s.execute(
"""
CREATE KEYSPACE udt_test_register_before_connecting
WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }
"""
)
s.set_keyspace("udt_test_register_before_connecting")
s.execute("CREATE TYPE user (age int, name text)")
s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)")
s.execute(
"""
CREATE KEYSPACE udt_test_register_before_connecting2
WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }
"""
)
s.set_keyspace("udt_test_register_before_connecting2")
s.execute("CREATE TYPE user (state text, is_cool boolean)")
s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)")
# now that types are defined, shutdown and re-create Cluster
c.shutdown()
c = Cluster(protocol_version=PROTOCOL_VERSION)
User1 = namedtuple("user", ("age", "name"))
User2 = namedtuple("user", ("state", "is_cool"))
c.register_user_type("udt_test_register_before_connecting", "user", User1)
c.register_user_type("udt_test_register_before_connecting2", "user", User2)
s = c.connect()
s.set_keyspace("udt_test_register_before_connecting")
s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User1(42, "bob")))
result = s.execute("SELECT b FROM mytable WHERE a=0")
self.assertEqual(1, len(result))
row = result[0]
self.assertEqual(42, row.b.age)
self.assertEqual("bob", row.b.name)
self.assertTrue(type(row.b) is User1)
# use the same UDT name in a different keyspace
s.set_keyspace("udt_test_register_before_connecting2")
s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User2("Texas", True)))
result = s.execute("SELECT b FROM mytable WHERE a=0")
self.assertEqual(1, len(result))
row = result[0]
self.assertEqual("Texas", row.b.state)
self.assertEqual(True, row.b.is_cool)
self.assertTrue(type(row.b) is User2)
c.shutdown()
示例9: test_for_schema_disagreement_attribute
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_for_schema_disagreement_attribute(self):
"""
Tests to ensure that schema disagreement is properly surfaced on the response future.
Creates and destroys keyspaces/tables with various schema agreement timeouts set.
First part runs cql create/drop cmds with schema agreement set in such away were it will be impossible for agreement to occur during timeout.
It then validates that the correct value is set on the result.
Second part ensures that when schema agreement occurs, that the result set reflects that appropriately
@since 3.1.0
@jira_ticket PYTHON-458
@expected_result is_schema_agreed is set appropriately on response thefuture
@test_category schema
"""
# This should yield a schema disagreement
cluster = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=0.001)
session = cluster.connect(wait_for_all_pools=True)
rs = session.execute("CREATE KEYSPACE test_schema_disagreement WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}")
self.check_and_wait_for_agreement(session, rs, False)
rs = session.execute("CREATE TABLE test_schema_disagreement.cf (key int PRIMARY KEY, value int)")
self.check_and_wait_for_agreement(session, rs, False)
rs = session.execute("DROP KEYSPACE test_schema_disagreement")
self.check_and_wait_for_agreement(session, rs, False)
# These should have schema agreement
cluster = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=100)
session = cluster.connect()
rs = session.execute("CREATE KEYSPACE test_schema_disagreement WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}")
self.check_and_wait_for_agreement(session, rs, True)
rs = session.execute("CREATE TABLE test_schema_disagreement.cf (key int PRIMARY KEY, value int)")
self.check_and_wait_for_agreement(session, rs, True)
rs = session.execute("DROP KEYSPACE test_schema_disagreement")
self.check_and_wait_for_agreement(session, rs, True)
示例10: makeConnection
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def makeConnection():
ip_address = findIP()
notResolved = True
while notResolved:
notResolved=False
try:
userpass = findUserPass()
ap = PlainTextAuthProvider(username=userpass[0], password=userpass[1])
bCluster=Cluster([ip_address],connection_class=AsyncoreConnection,auth_provider=ap)
bSpace = bCluster.connect()
except Exception as er:
redFlag = ['AuthenticationFailed','username','password','incorrect']
test = filter(lambda x: x.lower() in str(er).lower(), redFlag)
if len(test)==len(redFlag): #all redFlags words exists on message
print 'provided username doesnt work. trying default:'
ap = PlainTextAuthProvider(username='cassandra', password='cassandra')
try:
bCluster=Cluster([ip_address],connection_class=AsyncoreConnection,auth_provider=ap)
bSpace=bCluster.connect()
bSpace.execute("ALTER USER cassandra with password 'merogharanuwakotmaparchhatimrokahaparchha'")
except Exception as er:
print er
ap = PlainTextAuthProvider(username='cassandra', password='merogharanuwakotmaparchhatimrokahaparchha')
bCluster=Cluster([ip_address],connection_class=AsyncoreConnection,auth_provider=ap)
bSpace=bCluster.connect()
bSpace.execute("CREATE USER %s with password '%s' SUPERUSER" % (userpass[0],userpass[1]))
print ('The username and password created. Now trying login again')
bCluster.shutdown()
notResolved=True
else:
raise
return bCluster, bSpace
示例11: test_session_no_cluster
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_session_no_cluster(self):
"""
Test session context without cluster context.
@since 3.4
@jira_ticket PYTHON-521
@expected_result session should be created correctly. Session should shutdown correctly outside of context
@test_category configuration
"""
cluster = Cluster(**self.cluster_kwargs)
unmanaged_session = cluster.connect()
with cluster.connect() as session:
self.assertFalse(cluster.is_shutdown)
self.assertFalse(session.is_shutdown)
self.assertFalse(unmanaged_session.is_shutdown)
self.assertTrue(session.execute('select release_version from system.local')[0])
self.assertTrue(session.is_shutdown)
self.assertFalse(cluster.is_shutdown)
self.assertFalse(unmanaged_session.is_shutdown)
unmanaged_session.shutdown()
self.assertTrue(unmanaged_session.is_shutdown)
self.assertFalse(cluster.is_shutdown)
cluster.shutdown()
self.assertTrue(cluster.is_shutdown)
示例12: test_raise_error_on_control_connection_timeout
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_raise_error_on_control_connection_timeout(self):
"""
Test for initial control connection timeout
test_raise_error_on_control_connection_timeout tests that the driver times out after the set initial connection
timeout. It first pauses node1, essentially making it unreachable. It then attempts to create a Cluster object
via connecting to node1 with a timeout of 1 second, and ensures that a NoHostAvailable is raised, along with
an OperationTimedOut for 1 second.
@expected_errors NoHostAvailable When node1 is paused, and a connection attempt is made.
@since 2.6.0
@jira_ticket PYTHON-206
@expected_result NoHostAvailable exception should be raised after 1 second.
@test_category connection
"""
get_node(1).pause()
cluster = Cluster(contact_points=['127.0.0.1'], protocol_version=PROTOCOL_VERSION, connect_timeout=1)
with self.assertRaisesRegexp(NoHostAvailable, "OperationTimedOut\('errors=Timed out creating connection \(1 seconds\)"):
cluster.connect()
cluster.shutdown()
get_node(1).resume()
示例13: test_submit_schema_refresh
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_submit_schema_refresh(self):
"""
Ensure new new schema is refreshed after submit_schema_refresh()
"""
cluster = Cluster(protocol_version=PROTOCOL_VERSION)
cluster.connect()
self.assertNotIn("newkeyspace", cluster.metadata.keyspaces)
other_cluster = Cluster(protocol_version=PROTOCOL_VERSION)
session = other_cluster.connect()
session.execute(
"""
CREATE KEYSPACE newkeyspace
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
""")
future = cluster.submit_schema_refresh()
future.result()
self.assertIn("newkeyspace", cluster.metadata.keyspaces)
session.execute("DROP KEYSPACE newkeyspace")
cluster.shutdown()
other_cluster.shutdown()
示例14: test_pool_with_host_down
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_pool_with_host_down(self):
"""
Test to ensure that cluster.connect() doesn't return prior to pools being initialized.
This test will figure out which host our pool logic will connect to first. It then shuts that server down.
Previouly the cluster.connect() would return prior to the pools being initialized, and the first queries would
return a no host exception
@since 3.7.0
@jira_ticket PYTHON-617
@expected_result query should complete successfully
@test_category connection
"""
# find the first node, we will try create connections to, shut it down.
cluster = Cluster(protocol_version=PROTOCOL_VERSION)
cluster.connect()
hosts = cluster.metadata.all_hosts()
address = hosts[0].address
node_to_stop = int(address.split('.')[-1:][0])
try:
force_stop(node_to_stop)
wait_for_down(cluster, node_to_stop)
# Attempt a query against that node. It should complete
cluster2 = Cluster(protocol_version=PROTOCOL_VERSION)
session2 = cluster2.connect()
session2.execute("SELECT * FROM system.local")
cluster2.shutdown()
finally:
start(node_to_stop)
wait_for_up(cluster, node_to_stop)
cluster.shutdown()
示例15: test_invalid_protocol_negotation
# 需要导入模块: from cassandra.cluster import Cluster [as 别名]
# 或者: from cassandra.cluster.Cluster import connect [as 别名]
def test_invalid_protocol_negotation(self):
"""
Test for protocol negotiation when explicit versions are set
If an explicit protocol version that is not compatible with the server version is set
an exception should be thrown. It should not attempt to negotiate
for reference supported protocol version to server versions is as follows/
1.2 -> 1
2.0 -> 2, 1
2.1 -> 3, 2, 1
2.2 -> 4, 3, 2, 1
3.X -> 4, 3
@since 3.6.0
@jira_ticket PYTHON-537
@expected_result downgrading should not be allowed when explicit protocol versions are set.
@test_category connection
"""
upper_bound = get_unsupported_upper_protocol()
if upper_bound is not None:
cluster = Cluster(protocol_version=upper_bound)
with self.assertRaises(NoHostAvailable):
cluster.connect()
cluster.shutdown()
lower_bound = get_unsupported_lower_protocol()
if lower_bound is not None:
cluster = Cluster(protocol_version=lower_bound)
with self.assertRaises(NoHostAvailable):
cluster.connect()
cluster.shutdown()