FedericoCeratto/bottle-cork

Understanding the populate_mongodb_backend() function

Closed this issue · 3 comments

simple_webapp_using_mongodb.py starts with a function:

populate_mongodb_backend()

I understand that it populates the database with:

  • admin user to users collection
  • admin, editor and user roles to roles collection

but I ran my app containing this function once and it went through fine, I ran it again and I got:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: cork-example
.users.$login_1  dup key: { : "admin" }

I understand the error, that there is a duplicate, but I don't understand why the function is included like that - is it intended to run every time the program is run?

Or is it intended to just be run once and then commented out?

I don't think I could do the latter as it is intertwined with the next part of the code:

mb = populate_mongodb_backend()
aaa = Cork(backend=mb, email_sender='federico.ceratto@gmail.com', smtp_url='smtp://smtp.magnet.ie')

and aaa is then used frequently thoughout the rest of the code.

The example application is meant to be start and populate the database under the assumption that the database is empty.

The function that populates the database is assigned to the variable mb.

Then mb is a value assigned to the backend parameter of aaa, an instantiation of the Cork class.

aaa is then used throughout the rest of the program (aaa.login and aaa.register etc).

I cannot therefore comment out the function, because aaa seems to depend on it being there.

I cannot leave the function in though, because it seems it is causing the duplicate error?

To clarify:

  • I delete cork-example database.
  • I run the application once (database is created and populated).
  • I run the application again, and a duplicate error occurs.

Solution (i think)

I looked at this tutorial's code and noticed that backend didn't seem to be assigned the value of a function, so I commented out the populate_mongodb_backend() function (as the database has already been populated) and modifed the code to the following and now I can login and access all admin pages etc:

hostname = os.environ['OPENSHIFT_MONGODB_DB_URL']
connection = pymongo.MongoClient(host=hostname)
mb = MongoDBBackend(db_name='cork-example', initialize=True,hostname = hostname)
aaa = Cork(backend=mb, email_sender='federico.ceratto@gmail.com', smtp_url='smtp://smtp.magnet.ie')