I wrote a script that performs some operations on a MongoDB database. Like inserts, queries, listing dbs and collections.
The function I created that selects a database works fine if I run it from another script. But crashes with this error if I run the script stand alone:
Traceback (most recent call last):
File ".\ec2_mongo.py", line 212, in <module>
main()
File ".\ec2_mongo.py", line 194, in main
mongo_select_all()
File ".\ec2_mongo.py", line 113, in mongo_select_all
mydb, instance_col = set_db()
File ".\ec2_mongo.py", line 62, in set_db
instance_col = mydb[instance_col]
TypeError: string indices must be integers
What confuses me is that the lines that works when the script is called from another one, crashes when the script runs on it's own.
These are the lines in question:
instance_col = 'ec2_list-' + today
instance_col = mydb[instance_col]
Here is the function I wrote that only crashes when the script is run on it's own:
def connect_db():
try:
myclient = MongoClient(
host = "mongodb://localhost:27017/",
serverSelectionTimeoutMS = 3000 # 3 second timeout
)
except errors.ServerSelectionTimeoutError as e:
# set the client instance to 'None' if exception
myclient = None
# catch pymongo.errors.ServerSelectionTimeoutError
print ("pymongo ERROR:", e)
return myclient
def set_db():
myclient = connect_db()
today = datetime.today()
today = today.strftime("%m-%d-%Y")
if __name__ == '__main__':
message = "Select Database"
banner(message)
print(Fore.CYAN + "Available MongoDB Databases:")
if myclient != None:
# the list_database_names() method returns a list of strings
database_names = myclient.list_database_names()
counter = 1
for db in database_names:
message = str(counter) + '. ' + db
print(message)
counter = counter + 1
print ("There are", len(database_names), "databases.\n")
print(f"Please select a database. Enter a number 1 through {len(database_names)}.")
choice = input("Enter a number: ")
if is_digit(choice) == True:
if int(choice) > counter:
print("Wrong selection.")
set_db()
choice = int(choice)
choice = choice - 1
mydb = database_names[choice]
print(f"You've selected: {mydb}\n")
else:
print("Must enter a digit. Try again.\n")
set_db()
## Run as a stand alone script
instance_col = 'ec2_list-' + today
print(f"***Instance col type: {type(instance_col)}***")
instance_col = mydb[instance_col]
print(f"Type MYDB: {mydb}")
time.sleep(10)
else:
# Called from
mydb = myclient['aws_ec2_list']
print(f"Type MYDB: {mydb}")
time.sleep(10)
instance_col = 'ec2_list-' + today
print(f"***Instance col type: {type(instance_col)}***")
time.sleep(30)
instance_col = mydb[instance_col]
return mydb, instance_col