Search code examples
pythoncassandrakeyerrornosql

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


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! :)


Solution

  • 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')