cassandra - 'CREATE' in Python String causing KeyError with " 'class' "


Keywords:python 


Question: 

I'm trying to make a class of commands for Cassandra (A NoSQL database) using "Python-Driver". You can use session.execute() to run SQL commands on your Database. Anyway, I'm trying to make 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 issue 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 = sign in my string in Sublime Text is Red while the usual String color is yellow. If I take out "CREATE" from the string though, the equals sign will return to the color yellow!

Is this because Python already recognizes CREATE as SQL syntax and doesn't like the way I'm declaring the String with .format()? Any help would be great! :)


2 Answers: 

When using format you need to escape curly braces that are meant to be literal curly braces, e.g.

"CREATE {} WITH REPLICATION = \
    {{ 'class' : '{}', 'replication_factor' : {}  }};".format('a','b','c')
 

You have an error in your string.format syntax - you get the same error just trying to format that string the way you are doing..

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 issue is that you need to double the { and } literals for this to work.

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 curly-brace characters in python string and also use .format on it? for more details.