2

I'm writing the backend of my app in Python and writing to a PyMongo database.

I'm setting up a few servers which I'd like to run simultaneously as nodes in a blockchain. In my prototype, I need each node to create there own collection in my database for their version of the blockchain, so for example blockchain-{insert node_id here} for each.

I'm pretty new to python and have been self teaching myself but struggling to combine .format method with creating these collections.

I know that this works:

client = MongoClient('mongodb://localhost:27017/')
db = client.my_blockchain
col_blockchain = db.name_of_blockchain

Result: Collection named "name_of_blockchain"

But when I try the following, I get an error:

col_blockchain = db['col_my_blockchain_{}'].format(node_id)

Result: Error:

TypeError: 'Collection' object is not callable. If you meant to call the 'format' method on a 'Collection' object it is failing because no such method exists.

Or when I try to save the name in a variable, I don't get a dynamic answer:

    col_blockchain_name = 'col_my_blockchain_{}'.format(node_id)
    col_blockchain = db.col_blockchain_name 

Result: Collection named "col_blockchain_name" for each server running (so not dynamic)

2 Answers 2

5

This code:

col_blockchain = db['col_my_blockchain_{}'].format(node_id)

is looking for a dictionary element called col_my_blockchain_{} and when it has retrieved that it's trying to call the string format function on it. What you want to do is:

col_blockchain = db['col_my_blockchain_{}'.format(node_id)]

Which forms the dictionary key fully before trying to access it. All you need to do is move the ]

Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly - thanks so much! It now seems so obvious, I can't believe I didn't try that
-1

Use eval keyword, for calling mongo collection

eval('col_my_blockchain.{}'.format(node_id))

this works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.