How can I use the mongolab add-on to Heroku from python?

前端 未结 5 1326
旧时难觅i
旧时难觅i 2021-01-14 13:43

The documentation only talks about how to do it from ruby.

5条回答
  •  天涯浪人
    2021-01-14 14:28

    I think something like this should work:

    import os
    import sys
    import pymongo
    
    
    mongo_url = os.getenv('MONGOLAB_URI', 'mongodb://localhost:27017')
    db_name = 'mongotest'
    
    if __name__ == '__main__':
      try:
       connection = pymongo.Connection(mongo_url)
       if 'localhost' in self.mongo_url:
         db_name = 'my_local_db_name'
       else:
         db_name = self.mongo_url.rsplit('/',1)[1]
       database = connection[db_name]
      except:
       print('Error: Unable to Connect')
       connection = None
    
    if connection is not None:
      database.test.insert({'name': 'foo'})
    

提交回复
热议问题