3

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

Community
  • 1
  • 1
Nico
  • 399
  • 1
  • 15

3 Answers3

6

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')
lemonhead
  • 5,328
  • 1
  • 13
  • 25
3

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.

Community
  • 1
  • 1
ootwch
  • 930
  • 11
  • 32
0

Use this

"CREATE KEYSPACE {} WITH REPLICATION={{ 'class' : '{}', 'replication_factor' : {}}};".format(keyspace,'SimpleStrategy',1)

You need to escape curly braces that are meant to be literal curly braces, so use one more curly braces to escape them as above.

Suparna Raut
  • 71
  • 1
  • 5