"CREATE" in Python String throwing KeyError with "class"
I am trying to create a command class for Cassandra (NoSQL database) using "Python-Driver". You can use session.execute()
to run SQL commands on your database. Anyway, I am trying to create a function to create a keyspace.
Here is the code:
def createKeySpace(self, title, class_type='SimpleStrategy', replication_factor='3'):
self.session.execute("CREATE KEYSPACE {} WITH REPLICATION = \
{ 'class' : '{}', 'replication_factor' : {} };\
".format(title, class_type, replication_factor))
The problem is, if I try to use this function, I get the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "db_commands.py", line 12, in createKeySpace
".format('CREATE', title, class_type, replication_factor))
KeyError: " 'class' "
Something I think is worth noting: I noticed that the character =
on my string in Sublime Text is red and the normal String color is yellow. If I pull "CREATE" from the string, the equal sign reverts to yellow!
Is this because Python already recognizes CREATE as SQL syntax and doesn't like how I declare String with .format ()? Any help would be great! :)
source to share
You have an error in your string.format syntax - you get the same error, just try to format that string the way you do.
title="Title"
class_type="Class_Type"
replication_factor="Rep_Factor"
print("CREATE KEYSPACE {} WITH REPLICATION = { 'class' : '{}', 'replication_factor' : {} };".format(title, class_type, replication_factor))
Traceback (most recent call last):
File "<input>", line 3, in <module>
KeyError: " 'class' "
The problem is that you need to double the literals {
and to do this }
.
print("CREATE KEYSPACE {} WITH REPLICATION = \
{{ 'class' : '{}', 'replication_factor' : {} }};\
".format(title, class_type, replication_factor))
CREATE KEYSPACE Title WITH REPLICATION = { 'class' : 'Class_Type', 'replication_factor' : Rep_Factor };
Check How can I print literal shapes in curly braces in a python string and also use .format on it? for more details.
source to share